Using Margin on Flexbox children

Hey guys, I have a quick question about Flexbox.

I am able to achieve divs with 50% width’s ok, but once I add margins to the child elements the layout breaks. (I noticed if the widths were fixed then the margins don’t affect anything - but I want to be able to have fluid widths.) I thought perhaps using the justify-content: space-betweeen would do the trick, but again the widths need to be fixed…? Surely with all the bells and whistles Flexbox offers - this is a simple thing to achieve?

.flex-container {
    -webkit-flex-direction: row;
    flex-direction: row;
    -webkit-flex-wrap: wrap;
    flex-wrap: wrap;
    -webkit-justify-content: space-between;
    justify-content: space-between;
    -webkit-align-content: flex-start;
    align-content: flex-start;
    -webkit-align-items: flex-start;
    align-items: flex-start;
}
.flex-container > div {
	box-sizing: border-box;
	position:relative;
	background-color:rgba(67,66,68, 1);
	height:250px;
	text-align: center;
    -webkit-flex: 0 1 50%;
    flex: 0 1 50%;
    -webkit-align-self: auto;
    align-self: auto;
}

      <div class="flex-container">
            <div class="flex-item"><p>Box 1</p></div>
            <div class="flex-item"><p>Box 2</p></div>
            <div class="flex-item"><p>Box 3</p></div>
            <div class="flex-item"><p>Box 4</p><</div>
      </div>

I can’t believe it took me so long to figure out.
Your css is missing one very vital property:-

.flex-container {
  display: flex;
}

Edit: Note I reduced the flex-basis and enabled flex-grow to fill the width, assuming that’s what you want.

Thanks so much SamA74. :smile:

Sorry, I actually did have the display:flex; in my original work (but forgot to paste it into the example - LOL!) But now that I have changed the flex-basis/flex-grow values it is working like a charm.

I am still getting my head around how Flexbox works, so I’m a little late to the party…

You are not alone there. :smiley:

What I sometimes do is set basis to an em value with shrink and grow. That makes boxes fill the available width, but wrap on smaller screens without the need for queries.

2 Likes

I have some common flexbox patterns in a codepen here that you might find useful in the future.:slight_smile:

3 Likes

Awesome - thanks for the tip. :slight_smile:

Great, thanks Paul, I’ll check it out. :slight_smile:

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