absolute不适用于flex元素的孙辈



如何将.top_box固定在.content的头部?

对于当前代码,.top_box始终与.content一起滚动。

.wrapper {
height: 160px;
display: flex;
flex-direction: column;
}
.title_container {
background: pink;
}
.content {
height: 0;
flex: auto;
position: relative;
overflow-y: auto;
overflow-x: hidden;
background-color: bisque;
}
.top_box {
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 16px;
background: royalblue;
}
.scroll_fill {
height: 500px;
}
<div class="wrapper">
<div class="title_container">anyString</div>
<div class="content">
<div class="top_box"></div>
<div class="scroll_fill"></div>
</div>
</div>

您只需更改代码中HTML元素的顺序,并在.item之前编写.top。如果你这样做,你也可以删除大部分CSS,因为这是不必要的。

这里有一个完整的例子:

.box1 {
height: 600px;
display: flex;
flex-direction: column;
}
.box2 {
background: pink;
}
.box3 {
background-color: red;
}
.top {
width: 300px;
height: 5px;
background: blue;
}
.item {
height: 1000px;
}
<div class="box1">
<div class="box2">anyString</div>
<div class="box3">
<div class="top"></div>
<div class="item"></div>
</div>
</div>

还有一些其他事情:我不建议只使用divs并将它们命名为box1、box2、box3。相反,给它们起一些名字来描述它们的用途和含义,比如包装器、top_container、bottom_conainer、top_item、content:CSS命名惯例。

您还可以使用具有语义的特定标签:Sematic HTML5 Elements

希望能帮助

.wrapper {
height: 160px;
display: flex;
flex-direction: column;
}
.title_container {
background: pink;
}
.content {
height: 0;
flex: auto;
position: relative;
overflow: hidden;
background-color: bisque;
}
.contentInner {
height: 100%;
width: 100%;
overflow-y: auto;
overflow-x: hidden;
}
.top_box {
position: absolute;
top: 0;
left: 0;
width: 300px;
height: 16px;
background: royalblue;
}
.scroll_fill {
height: 500px;
}
<div class="wrapper">
<div class="title_container">anyString</div>
<div class="content">
<div class="top_box"></div>
<div class="contentInner">
<div class="scroll_fill"></div>
</div>
</div>
</div>

最新更新