使用父级的 100% 高度而不明确定义父级的高度

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

我有这个非常简单的片段:

.parent {
  display: flex;
  background-color: blue;
}

.child100 {
  width: 6px;
  height: calc(100% - 5px);
  background-color: red;
}
<body>
  <div class="parent">
    <div class="child100"></div>
    <div class="childContent">
      <table>
        <tr>
          <th>
            1
          </th>
          <th>
            2
          </th>
        </tr>
        <tr>
          <th>
            3
          </th>
          <th>
            4
          </th>
        </tr>
      </table>
    </div>
  </div>
</body>

height: calc(100% - 5px);
没有任何效果,如果我将
height: 100%
设置为
html body and parent tags
.
我不想以像素为单位明确定义父级的高度,而是希望它适合其内容(采用表格的高度)。
我不希望
child100
的位置是绝对的,因为
parent
div 是一个非常长的溢出元素的一部分,滚动时会卡在
child100
上,而不是在
table
旁边。
此外,省略
height
.child100
属性并为另一个孩子添加
margin-bottom: -5px
将影响背景颜色所见的整个
parent
元素的高度。

css
1个回答
1
投票

删除高度定义并添加底部边距。 flexbox 的拉伸对齐将为您完成这项工作。

.parent {
  display: flex;
  background-color: lightblue;
}

.child100 {
  width: 6px;
  margin-bottom: 5px;
  background-color: red;
}
<body>
  <div class="parent">
    <div class="child100"></div>
    <div class="childContent">
      <table>
        <tr>
          <th>
            1
          </th>
          <th>
            2
          </th>
        </tr>
        <tr>
          <th>
            3
          </th>
          <th>
            4
          </th>
        </tr>
      </table>
    </div>
  </div>
</body>

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