【问题标题】:flexbox margin cause overflowflexbox 边距导致溢出
【发布时间】:2016-09-12 10:40:21
【问题描述】:

我有一个 flexbox 溢出的小问题:

html

<div class="first">
            <div class="child"></div>
            <div class="child"></div>
            <div class="child"></div>
</div>

css

* {
    box-sizing: border-box;
}

body {
    margin: 50px;
}
.first {
    display: flex;
    flex-flow: row nowrap;
}

.child {
    background: red;
    border: 1px blue solid;
    height: 10px;
    flex: 0 0 33.3%;

    margin-right: 10px;
}

.first :last-child {
    flex: 0 0 33.4%;
}

问题是最后一个孩子溢出了,为什么?我用 box-sizing 来代替边框?

【问题讨论】:

  • box-sizing 对边距没有影响!你想做什么?
  • 好吧,如何在子项之间添加边距而不导致溢出

标签: html css grid flexbox


【解决方案1】:

如何在子元素之间添加边距而不导致溢出

我认为这就是你想要做的:

* {
  box-sizing: border-box;
}

body {
  margin: 50px;
}

.first {
  display: flex;
  flex-flow: row nowrap;
  border:1px solid green;
}

.child {
  background: red;
  border: 1px blue solid;
  height: 10px;
  flex: 1; /* equal widths */
  margin-right: 10px;
}
.first :last-child {
  margin-right: 0;
}
<div class="first">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

或者,您可以使用calc 设置子宽度并在弹性容器上使用justify-content:space-between

* {
  box-sizing: border-box;
}
body {
  margin: 50px;
}
.first {
  display: flex;
  flex-flow: row nowrap;
  border: 1px solid green;
  justify-content: space-between;
}
.child {
  background: red;
  border: 1px blue solid;
  height: 10px;
  width: calc((100% - 20px)/3);
  /* or */
  flex: 0 0 calc((100% - 20px)/3);
}
<div class="first">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2020-10-27
    • 2020-06-26
    • 1970-01-01
    • 2013-10-19
    • 2021-06-17
    相关资源
    最近更新 更多