父元素按钮高度的span 100%。

11

我有以下的标记

<button class="filter"><div class="radio"><div class="circle"></div></div> <span>Account Management</span></button>

以及CSS

.filter {
    font-size: 3vw;
    text-align: left;
    line-height: 1.6;
    padding: 0px;
    display: block;
    height:auto;
    overflow: hidden;
    margin-bottom: 3px;
}
.filter span {
    background: $leithyellow;
    height: 100%;
    overflow:auto;
    display: block;
    width: calc(100% - 60px);
    float: left;
    margin-left:10px;
    padding-left:20px;
}

我无法使span元素高度扩展到按钮的100%。 这可行吗?

2个回答

12
  1. 将父元素的 display: flex 属性设置为,
  2. 将子元素的 align-self: stretch 属性设置为。

这样可以让子 div/button 的高度自适应父元素的高度,无需使用任何技巧。

如果使用 position: absolute 而不是 flex-box,在添加更多内容或稍后重新排列时,情况最终会变得非常糟糕。


在2023年,这是正确/最佳答案,而且它适用于身高未定义的父母,这是一个巨大的优势。 - Juanma Guerrero

10

仅当祖先元素的高度定义正确时,高度才会生效。如果您希望高度生效,那就有点棘手了。您可以使用我最喜欢的方法之一,但需要确保它在所有情况下都有效:

  1. 给父级元素添加 position: relative;
  2. 给需要完整 heightwidth 的元素添加 position: absolute;
  3. 将该元素的各个边的值设为 0

代码片段

.parent {
  position: relative;
  width: 100px;
  height: 50px;
  background: red;
}
.parent .child {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: skyblue;
}
<div class="parent">
  <span class="child"></span>
</div>

在上面的片段中,值得注意的是,如果你提供以下内容,它也可以工作:

.parent {
  position: relative;
  width: 100px;
  height: 50px;
  background: red;
}
.parent .child {
  position: absolute;
  width: 100%;
  height: 100%;
  background: skyblue;
}
<div class="parent">
  <span class="child"></span>
</div>

使用这种方法的一个好处是,您无需使用危险的calc

.parent {
  position: relative;
  width: 150px;
  height: 50px;
  background: red;
}
.parent .child {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 60px;
  background: skyblue;
}
<div class="parent">
  <span class="child"></span>
</div>

注意: 与此相关,您还可以查看这个问题和答案: Calc() 替代品用于固定侧边栏与内容?


1
全面的回答,谢谢。我非常决心保持元素的相对性,但这个方法很有效。 - LeBlaireau

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接