Skip to content Skip to sidebar Skip to footer

Flexbox: When Wrapping In A Row How Can I Stack Two+ Elements Without Extra Markup?

UPDATE: So I was able to make this work with Flexbox Codepen However, as some in the community point out, the caveats (such as fixed heights) prove that CSS grid is the best case f

Solution 1:

As others have said, the CSS Grid Layout would probably be easier and cleaner for your intents. Flexbox is designed for its elements to flow in one direction, and does not act like a table or grid.

But relying on Flexbox, I've recreated the best that I can think of using. Except that it does involve extra markup (can't really achieve all your goals - limitations of Flexbox).

It sets an extra class .flexcol on a div element, which will act as a wrapper for elements you want stacked.

.flexcol {
  flex-direction: column;
  align-items: stretch;
}

body {
  display: flex;
  flex-wrap: wrap;
}

.full-width {
  flex: 100%;
}

.fifty {
  flex: 0050%;
}

.one-third {
  flex: 0033%;
}

.twnty-five {
  flex: 0025%;
}

div {
  display: flex;
  min-height: 100px;
  align-items: center;
  justify-content: center;
  text-align: center;
  border: 1px solid #DFDFDF;
  box-sizing: border-box;
}

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
<divclass="full-width">full-width</div><divclass="fifty">fifty</div><divclass="fifty">fifty</div><divclass="one-third">one-third</div><divclass="one-third">one-third</div><divclass="one-third flexcol"><div>one-third stack top</div><div>one-third stack bottom</div></div><divclass="twnty-five">twnty-five</div><divclass="twnty-five">twnty-five</div><divclass="twnty-five">twnty-five</div><divclass="twnty-five flexcol"><div>stack top</div><div>stack middle</div><div>stack bottom</div></div>

Post a Comment for "Flexbox: When Wrapping In A Row How Can I Stack Two+ Elements Without Extra Markup?"