Flex 项目中的 CSS width: 100% 有什么作用?

问题描述 投票:0回答:1

有人可以解释一下这个CSS是如何工作的吗?

这是我的 HTML 代码:

    <div class="wrapper">
      <div class="item-4">
        <h2>Item 4</h2>
        <button>Click me</button>
      </div>

      <div class="item-5">Item 5 QR code</div>
    </div>

这是我的 CSS 代码:

.wrapper {
  display: flex;

  border: 1px solid black;
  width: fit-content;
  margin: 0 auto;
}

.item-4, .item-5 {
  border: 1px solid red;
  background: white;
}

像这样的编码将导致 .wrapper 框位于屏幕中央。它的弹性项目:Item-4 和 Item-5 的宽度也适合其内容,这符合预期。

看这张图

.wrapper 框的宽度为 174.86px 看这张图

我不明白的是,如果现在我再添加一段CSS代码:

.item-4 {
  width: 100%;
}

item-4 的宽度突然扩大一些。其宽度经测量为 108.3px。 看这张图

108.3px这个数字是怎么计算出来的?为什么当我添加 CSS width: 100% 时,Item-4 中仅添加了一些空间?

html css
1个回答
0
投票

以下是逐步说明,可帮助您了解正在发生的情况:

.wrapper {
  display: flex;
  border: 1px solid black;
  width: fit-content;
  margin: 0 auto;
}

.item-4,
.item-5 {
  border: 1px solid red;
  background: white;
}
<div class="wrapper">
  <div class="item-4">
    <h2>Item 4</h2>
    <button>Click me</button>
  </div>

  <div class="item-5">Item 5 QR code</div>
</div>

<p>adding width: 100% and flex-shrink: 0;</p>

<div class="wrapper">
  <div class="item-4" style="width: 100%;flex-shrink:0;">
    <h2>Item 4</h2>
    <button>Click me</button>
  </div>

  <div class="item-5" style="flex-shrink:0;">Item 5 QR code</div>
</div>

<p>remove the flex-shrink: 0 to keep the default shrink behavior</p>

<div class="wrapper">
  <div class="item-4" style="width: 100%;">
    <h2>Item 4</h2>
    <button>Click me</button>
  </div>

  <div class="item-5">Item 5 QR code</div>
</div>

因此 item-4 将尝试获取所有父级宽度(使用 width: 100%),但这会将下一个项目推到外面,因此默认收缩行为将减小宽度以使它们都适合容器内。

© www.soinside.com 2019 - 2024. All rights reserved.