Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was under the impression that a margin can be added to flex items/children, and flexbox should automatically take that into account and calculate the correct spacing between the items.

I can't seem to get this working as I would like though.

Fiddle here: https://jsfiddle.net/dba5ehcw/1/

.flex-item{
    border: 1px solid blue;
    box-sizing: border-box;
    height: 160px;
    width: 50%;
}

So each flex item at the moment is half the width of the container, and they flow nicely next to each other.

I would like to be able to add a margin of say, 1em to the flex-items in order to give them some breathing room, but in doing so, they become larger than the 50% and no longer stack next to each other on the same line because they are too wide.

Is there a way to use margin on the flex-items and have the flexbox container take this into account and adjust (decrease) their widths accordingly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
446 views
Welcome To Ask or Share your Answers For Others

1 Answer

There are multiple ways to do this:

  • Use calc:

    .flex-item {
      width: calc(50% - 2em);
      margin: 1em;
    }
    

    .flex-container {
      border: 1px solid red;
      box-sizing: border-box;
      display: flex;
      flex-wrap: wrap;
      width: 320px;
    }
    .flex-item {
      border: 1px solid blue;
      box-sizing: border-box;
      height: calc(160px - 2em);
      width: calc(50% - 2em);
      margin: 1em;
    }
    <div class="flex-container">
      <div class="flex-item"></div>
      <div class="flex-item"></div>
      <div class="flex-item"></div>
      <div class="flex-item"></div>
      <div class="flex-item"></div>
      <div class="flex-item"></div>
    </div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...