首页 > 解决方案 > 弯曲孩子的孩子占据了所有的空间

问题描述

我有 2 个 div 是 flexed 元素的子元素。在其中一个中,我想要另一个 div,它只占用其内容所需的空间。相反,它占用了所有空间。

我究竟做错了什么?

这是我的演示:

.wrapper {
  width: 500px;
  height: 200px;
  display: flex;
  flex: 1;
}

.c-1 {
  height: 100%;
  flex: 3;
  
  background-color: green;
}

.c-2 {
  height: 100%;
  flex: 1;
  
  background-color: red;
}

.c-1-inner {
  height: 100%;
  background-color: blue;
}

.box {
  height: 15px;
  width: 15px;
  background-color: yellow;
}
<div class="wrapper">
  <div class="c-1">
    <div class="c-1-inner">
      <div class="box"></div>
    </div>
  </div>
  <div class="c-2"></div>
</div>

标签: cssflexbox

解决方案


这是你所追求的行为吗?width: fit-content;

.wrapper {
  width: 500px;
  height: 200px;
  display: flex;
  flex: 1;
}

.c-1 {
  height: 100%;
  flex: 3;
  
  background-color: green;
}

.c-2 {
  height: 100%;
  flex: 1;
  
  background-color: red;
}

.c-1-inner {
  height: 100%;
  width: fit-content;
  background-color: blue;
}

.box {
  height: 15px;
  width: 15px;
  background-color: yellow;
}
<div class="wrapper">
  <div class="c-1">
    <div class="c-1-inner">
      <div class="box"></div>
    </div>
  </div>
  <div class="c-2"></div>
</div>


推荐阅读