Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take 2 columns in 2-columns layout but not when 1-column layout in CSS grid without @media

Tags:

css

css-grid

The desired layout for wide screens:

enter image description here

The desired layout for narrow screens:

enter image description here

Initial CSS:

.Layout {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  grid-gap: 24px 40px;
}

If I'll set grid-column-start: span 2 for the third element, the layout will be simply broken (it' happen in CSS grid ignores minimal width specified in minmax() in second column question).

Please don't use the media queries because it will nullify the announced free-space-based responsiveness which became available in CSS grid.

Grid has two extremely powerful features for dealing with changes in available space.

<...>

Layout that relies on media queries is tied to the view-port, this isn’t modular β€” components within a system need to be able to adapt to the space they have available.

🌎 Getting to know CSS Grid Layout

Please say clearly: "it's impossible" if you are sure that it so and skilled in CSS grid.

like image 517
Takeshi Tokugawa YD Avatar asked Oct 26 '25 15:10

Takeshi Tokugawa YD


1 Answers

Use grid-column: 1/-1;

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  grid-gap: 24px 40px;
}

span {
  height: 50px;
  background: blue;
}

.more {
  grid-column: 1/-1;
  background: red;
}
<div class="box">
  <span></span>
  <span></span>
  <span class="more"></span>
  <span></span>
  <span></span>
</div>

That you can edit like below if you want to always have a maximum of 2 columns:

.box {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(max(240px,40vw), 1fr));
  grid-gap: 24px 40px;
}

span {
  height: 50px;
  background: blue;
}

.more {
  grid-column: 1/-1;
  background: red;
}
<div class="box">
  <span></span>
  <span></span>
  <span class="more"></span>
  <span></span>
  <span></span>
</div>
like image 68
Temani Afif Avatar answered Oct 29 '25 08:10

Temani Afif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!