Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-rectangular CSS grid elements

Tags:

css

css-grid

Suppose I wanted to use auto dense packing in a CSS grid layout. Is there any way of introducing non-rectangular region configurations? For instance an L-shaped region that cover two columns in one row and only one column in the next. I have tried explicitly naming the grid cells however this doesn't work.

like image 424
Bytes Avatar asked Mar 20 '18 16:03

Bytes


2 Answers

There is no support for non-rectangular grid items. From the spec:

Every grid item is associated with a grid area, a rectangular set of adjacent grid cells that the grid item occupies.

And:

Note: Non-rectangular or disconnected regions may be permitted in a future version of this module.

(which does not imply that such a feature has been planned, only that there is nothing stopping such a feature from being added in the future)

like image 152
BoltClock Avatar answered Oct 13 '22 04:10

BoltClock


While you can't technically create L-shaped grid items. You can layer items over each other with z-index.

Expanding on this, if you want gaps between the odd shapes, you can use a combination of grid-gap and outline like this:

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

.box1 {
  grid-column-start: 1;
  grid-row-start: 1;
  grid-row-end: 3;
}

.box2 {
  grid-column-start: 2;
  grid-column-end: 4;
  grid-row-start: 1;
  z-index: 1;
  outline: 10px solid white;
}

.box3 {
  grid-column-start: 3;
  grid-column-end: 7;
  grid-row-start: 1;
  grid-row-end: 5;
  text-align: right;
}

.box4 {
  grid-column-start: 2;
  grid-row-start: 2;
}

.box5 {
  grid-column-start: 3;
  grid-column-end: 5;
  grid-row-start: 2;
  z-index: 1;
  outline: 10px solid white;
}

.box6 {
  grid-column-start: 1;
  grid-column-end: 3;
  grid-row-start: 3;
  grid-row-end: 5;
}

.wrapper {
  background-color: #fff4e6;
}

.box {
  background-color: #ffd8a8;
  padding: 1em;
  color: #d9480f;
}
<div class="wrapper">
  <div class="box box1">One</div>
  <div class="box box2">Two</div>
  <div class="box box3">Three</div>
  <div class="box box4">Four</div>
  <div class="box box5">Five</div>
  <div class="box box6">Six</div>
</div>

Open on Codepen

like image 10
tekNorah Avatar answered Oct 13 '22 05:10

tekNorah