【问题标题】:Why child divs don't extend beyond flex row container [duplicate]为什么子 div 不会超出 flex 行容器 [重复]
【发布时间】:2020-01-06 17:40:07
【问题描述】:

在 codepen 中查看问题:https://codepen.io/pencillrpal/pen/QWLOLGv

我有一个 flex 容器,其中我将有一个水平滑块,其中的元素与整个页面宽度一样长。

但我意识到我无法控制子元素的宽度,因为它们总是有一个宽度使它们适合容器,并且它们不会超出它。

不过我发现了一个窍门。如果我将我的孩子 div 一个一个地包装到一个 div 中,它将按我的意愿工作。

为什么会这样?

.container {
  display: flex;
  flex-direction: row;
  justify-content: center;
  height: 40vh;
  max-width: 100%;
  overflow-x: hidden;
  border: 5px solid black;
  margin: 0 auto;
}

.box {
  position: relative;
  width: 90vw;
  margin: 10px;
  line-height: 10vh;
  text-align: center;
  background: black;
  color: white;
  border: 5px solid red;
}
<h1>Box should have 100vw width</h1>
<div class="container">
  <div class="box">
    <h3>Box</h3>
  </div>
  <div class="box">
    <h3>Box</h3>
  </div>
  <div class="box">
    <h3>Box</h3>
  </div>
</div>

<h1>This one has though</h1>
<div class="container">
  <div>
    <div class="box">
      <h3>Box</h3>
    </div>
  </div>
  <div>
    <div class="box">
      <h3>Box</h3>
    </div>
  </div>
  <div>
    <div class="box">
      <h3>Box</h3>
    </div>
  </div>
</div>

【问题讨论】:

  • 你的 h3 元素都没有正确关闭
  • 第一个重复解释第一个代码,第二个重复解释第二个代码

标签: html css


【解决方案1】:

可以控制 flex 子项的宽度。所有 flex 子节点都有默认的 flex 值来控制 flex-growflex-shrink 属性。禁用这些属性,您将可以控制宽度。

将这些行添加到您的 CSS 中。

/**
 * Disable flex grow and shrink so that it no longer tries to divide the
 * space between the .box elements.
 *
 * Use flex-basis or width to control the width of the element.
 */
.box {
    flex-grow: 0;
    flex-shrink: 0;
    flex-basis: 90vw;
    width: 90vw;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 2021-04-18
    相关资源
    最近更新 更多