Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css grid with nested div structure [duplicate]

Tags:

html

css

css-grid

I try to build a CSS Grid where some entries are nested in a div structure:

like that it works:

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  grid-template-rows: 1;
}

.cent {
  grid-column: 2;
  grid-row: 1;
}

.left {
  grid-column: 1;
  grid-row: 1;
}

.right {
  grid-column: 3;
  grid-row: 1;
}
<div class="wrapper">
  <div class="cent">center</div>
  <div class="left">left</div>
  <div class="right">right</div>
</div>

But if I start to nest my structure I can't access the column I want:

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  grid-template-rows: 1;
}

.cent {
  grid-column: 2;
  grid-row: 1;
}

.left {
  grid-column: 1;
  grid-row: 1;
}

.right {
  grid-column: 3;
  grid-row: 1;
}
<div class="wrapper">
  <div class="cent">center</div>
  <div>
    <!-- in reality there would be more divs and rows, I already have problems with one -->
    <div class="left">left</div>
    <div class="right">right</div>
  </div>
</div>

Can somebody give me tip on how to achieve the grid with a nested structure? Or do I have a complete wrong approach? (Unfortunately changing the order and structure of the elements in code would be very time consuming)

like image 413
Fabian Avatar asked Sep 19 '26 22:09

Fabian


1 Answers

Nested grids are possible, but make sure that the parent of the innermost divs does itself have display:grid. If you don't,

As these items are not direct children of the grid they do not participate in grid layout and so display in a normal document flow.

(from MDN: Basic concepts of grid layout.)

So all you need to do is assign those styles to the parent of the left and right divs.

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  grid-template-rows: 1;
}

.cent {
  grid-column: 2;
  grid-row: 1;
}

.cent + div {   /* this works for now, but you should choose a better selector for this one */
  display: grid;
  grid-column: 1 / 4;
  grid-row: 1;
}

.left {
  grid-column: 1;
  grid-row: 1;
}

.right {
  grid-column: 3;
  grid-row: 1;
}
<div class="wrapper">
  <div class="cent">center</div>
  <div>
    <!-- in reality there would be more divs and rows, I already have problems with one -->
    <div class="left">left</div>
    <div class="right">right</div>
  </div>
</div>
like image 116
Mr Lister Avatar answered Sep 21 '26 12:09

Mr Lister