设置高度 = "100% - relative top" 对于绝对定位的元素



下面是一个示例代码片段:

.tabs {
display: flex;
position: relative;
}
.tab {
height: 100px;
background: lightgray;
}
.content {
position: absolute;
left: 0;
width: 100%;
height: 100%;
display: none;
background: lightgreen;
}
.open .content {
display: block;
}
.footer {
height: 50px;
background: lightblue;
}
<div class="tabs">
<div class="tab">
<div class="header">Tab 1</div>
<div class="content">Content 1</div>
</div>
<div class="tab open">
<div class="header">Tab 2</div>
<div class="content">Content 2</div>
</div>
</div>
<div class="footer">Footer</div>

绿色内容的绝对位置高度等于其相对位置容器的高度。所以它和页脚重叠。是否有可能保持顶部位置相对,并将底部设置为0?比如:

.content {
position: absolute;
left: 0;
width: 100%;
top: relative; /* Not supported */
bottom: 0;
display: none;
background: lightgreen;
}

我可以显式地将top设置为20px。或者我可以使用JavaScript计算和设置它。是否有一个CSS唯一的解决方案没有预先计算的top值?

这里有一个想法,使用CSS网格来实现你想要的没有position:absolute

.tabs {
display: grid;
grid-auto-flow:column; /* column flow */
}
.tab {
display:contents; /* remove the tab div */
}
.header {
background: lightgray;
}
.content {
/* make all the content above each other*/
grid-row:2;
grid-column:1/span 20; /* use a big value here, at least equal to number of tab*/
/**/
height: 100px;
display: none;
background: lightgreen;
}
.open .content {
display: block;
}
.footer {
height: 50px;
background: lightblue;
}
<div class="tabs">
<div class="tab">
<div class="header">Tab 1</div>
<div class="content">Content 1</div>
</div>
<div class="tab open">
<div class="header">Tab 2</div>
<div class="content">Content 2</div>
</div>
</div>
<div class="footer">Footer</div>

你可以在页脚设置一个边距,将其与绿色内容分开。

.footer{
margin-top: 20px;
}

最新更新