Getting acquainted with CSS Grid

  <div class="grid-container">
    <h1>Yes</h1>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
  </div>

CSS:

.grid-container {
display: grid;
grid-auto-flow: column;
gap: 10px; 
}

Q1. Which Propery should I access so that heading tag consumes the whole first row. Thanks.

Until the experts come along this is my trial and error approach.

<div class="main-container">
    <h1>Yes</h1>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
    <p>6</p>
    <p>7</p>
    <p>8</p>
</div>
.main-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(4, 1fr);
  grid-auto-flow: column;
  place-items: center;
  gap: 10px;
}

.main-container h1 {
  grid-column: 1/-1; /* span all columns */
}

I would have thought separating the numbers into their own grid would make life easier though.

<div class="main-container">
  <h1>Yes</h1>
  <div class="numbers-container">
      <p>1</p>
      <p>2</p>
      <p>3</p>
      <p>4</p>
      <p>5</p>
      <p>6</p>
  </div>
</div>
.main-container {
  display: block;
  ...
}

.numbers-container {
  display: grid;
  ...
  grid-auto-flow: column;
  place-items: center;
  gap: 10px;
}
2 Likes

Not sure if you want to have fix 3 columns.

I you want to have as much columns in one row as possible it would be better to use flex instead of grid

3 Likes

You can do that just as easily with Grid. E.g. using auto-fit instead of a fixed number of rows:

3 Likes

I don’’t believe that’s the same though as you have basically 2 full width rows. You added an extra wrapper to achieve this so items 2 - 6 are separate grid items as such. :slight_smile:

With flex you can keep them all as siblings and just set the h1 to flex:1 0 100%.

There was talk of adding a span all for the implicit grid to cater for auto columns but I don’t think it’s got anywhere yet. Otherwise you have to use the explicit grid columns which are not then auto width.

In cases where there’s not a relationship between column and row then flex is usually the best tool. :slight_smile:

2 Likes

or just… dont put the header in the div? Use the header as… yaknow… a header?

3 Likes

Haha, yes, I got lost in my own experiments. Okay, so is this the simplest way to do it with Flexbox?

2 Likes

I didn’t put a header tag in the div. Didn’t get your point?

He means this:

<h1>Yes</h1>

<div class="grid-container">
  <p>1</p>
  <p>2</p>
  <p>3</p>
  <p>4</p>
</div>

As ralph points out… yes, you literally did. <h1>. Heading/Header 1.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.