Responsive flex box layout


#1

Hi all

I have a codepen here - https://codepen.io/anon/pen/dKWvMJ

Its a simple responsive flex box layout with list of 4 blocks that should go to two rows of two blocks at 700px

The blocks have right margins

When it goes to two rows the margins seem to break the layout and the blocks are stacked.

I know I could do this with div inside the li but is it possible to do it without adding margins to the div inside the li


#2

Hi @RachelR

Your link to codepen doesn't seem to work :blush:


#3

Sorry about that, it should now


#4

At 50% width you don't account for margins and padding. Setting box-sizing: border-box will take care of padding and borders, but you will have to go below 50% to account for margins.
I don't see why you have both flex-basis and width set.


#5

You also have to accommodate the 5px right margin which won't be helped with box-sizing as its outside the box.

I'd so something like this:

html {
  box-sizing: border-box;
  font-family: sans-serif;
}
*, *:before, *:after {
  box-sizing: inherit;
}

ul {
  border: 1px solid red;
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
}
li {
  flex: 1 0 0%;
  height: 100px;
  color: white;
  margin-right: 5px;
  box-sizing:border-box;
}
li div {
  background-color: red;
  height: 100%;
  padding: 10px;
}
li:nth-child(4) {
  margin-right: 0;
}

@media (max-width: 700px) {
  ul {flex-wrap: wrap;}
  li{flex:1 0 45%;flex-basis:calc(50% - 2.5px);margin-bottom:4px;}
  li:nth-child(2) {margin-right: 0;}
  li:nth-child(3), li:nth-child(4){margin-bottom:0;}
}

No need to state the obvious (i,e. the flex defaults) which save a few lines.

The 4 across needs no widths because flex-basis:0% combined with flex:grow:1 will automatically equalise all box widths on the first line (assuming only 4 elements are present at all times ).

When you go to 2 across then you need a basis to split only 2 on a line but you then need to accommodate the 5px right margin. I used calc in the above example to be exact but a percentage value less than say 48% would do but is a guesstimate.


#6

Using a value a little below and enabling flex-grow can do the trick, the grow fills any excess space.


#7

Yes that’s basically what I usually do and what I meant with that comment above. I was assuming flex grow was set to 1 as in my example :slight_smile:

The only problem is that it’s still a guesstimate as you have to work out if the percentage you shorten is actually less than the margin required. You could of course specify a much smaller percentage for extra safety but must be greater than 33.3% otherwise you’d get 3 across.

Using calc you can be exact but cries out for using css variables so that the margin value can be tied to the basis to avoid changing one but not the other.


#8

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.