2

Ok this is giving me quite an headache...

this is my code/example

https://codepen.io/anon/pen/xXpjYa

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

.imageContainer {
  flex: 1 0 30%;
  height: 200px;
  border: 5px solid black;
  background-color: deeppink;
  margin:15px;
}

.imageContainer:empty {
    height: 0;
    border: none;
};
 
<div class="flex">
    <div class="imageContainer">a</div>
    <div class="imageContainer">a</div>
    <div class="imageContainer">a</div>
    <div class="imageContainer">a</div>
    <div class="imageContainer"></div> 
    <div class="imageContainer"></div>
</div>

the problem is that I want to achieve/fix two things:

  • the far left and far right column should be touching the edge of the viewport
  • the fixed gap should be 30px and only the pink boxes stretch responsively
  • notice the last item (5) is slightly wider than the others...why??

please help! thanks!

Asons
  • 84,923
  • 12
  • 110
  • 165
Francesco
  • 24,839
  • 29
  • 105
  • 152

2 Answers2

1

You set the margin to be 15px, on .imageContainer this applies to all sides, including the sides between these imageContainers and the viewport. So basically your first ask and your second ask are fighting against each other.

You can set a margin on .imageContainer and a negative margin on the parent .flex to accomplish both.

The last visible item is longer because the two divs following it are collapsing and not showing, which affects the layout. If you add the css attribute box-sizing: border-box to your .imageContainer rule, it will fix this issue. You can also assigned a fixed height to .imageContainer, or add content to all of the .imageContainer divs to prevent this from happening.

See this codepen for the modified code.

Bricky
  • 2,572
  • 14
  • 30
1

Instead of margin use justify-content: space-between and set flex: 0 0 30% instead of flex: 1 0 30%. Last item is bigger because there is no border on other two.

body {
  margin: 0;
}
.flex {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.imageContainer {
  flex: 0 0 30%;
  height: 200px;
  border: 5px solid black;
  background-color: deeppink;
  margin: 15px 0;
}
.imageContainer:empty {
  height: 0;
  border: none;
}
<div class="flex">
  <div class="imageContainer">a</div>
  <div class="imageContainer">a</div>
  <div class="imageContainer">a</div>
  <div class="imageContainer">a</div>
  <div class="imageContainer"></div>
  <div class="imageContainer"></div>
</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • This approach makes it much harder to have a set distance between items. – Bricky Oct 05 '17 at 20:44
  • @Bricky Not really. – Nenad Vracar Oct 05 '17 at 20:46
  • You would need to set the children elements width to the (width of the parent container, minus (the number of gutters * width of the gutters)) / number of children elements. Otherwise you'll end up with off-set rows as the number of children elements grow. – Bricky Oct 05 '17 at 20:48