Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
452 views
in Technique[技术] by (71.8m points)

css - Using margin on flex items

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...