arthur
arthur

Reputation: 39

Css Grid Dynamic layouts

I am trying to make a dynamic grid layout containing 1-4 elements. They achieved something close to what I am looking for at https://css-tricks.com/exploring-css-grids-implicit-grid-and-auto-placement-powers/ under the "dynamic layouts" section. But slightly different.

enter image description here

The CSS for this layout:

.grid {
  display: grid;
}
.grid :nth-child(2) {
  grid-column-start: 2;
}
.grid :nth-child(3):last-child {
  grid-column-start: span 2;
}

I am trying to do something similar but different, but I cannot get it. This is a picture of what I want to achieve:

enter image description here

Upvotes: 0

Views: 279

Answers (1)

A Haworth
A Haworth

Reputation: 36646

You can use the CSS nth-last-child selector to spot when the first child is the first of three children.

.grid {
  display: grid;
}

.grid :nth-child(2) {
  grid-column-start: 2;
}

.grid :nth-child(1):nth-last-child(3) {
  grid-row-start: span 2;
}


/**/

.grid {
  width: 300px;
  aspect-ratio: 1;
  grid-gap: 5px;
  outline: 2px solid red;
  vertical-align: top;
  margin: 10px;
  counter-reset: num;
}

.grid * {
  border: 2px solid;
  font-size: 30px;
  box-sizing: border-box;
  font-family: sans-serif;
  display: grid;
  place-content: center;
}

.grid *:before {
  content: counter(num);
  counter-increment: num;
}
<div class="grid">
  <div></div>
</div>
<div class="grid">
  <div></div>
  <div></div>
</div>
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Upvotes: 3

Related Questions