运行下面的代码片段,以查看我要实现的目标。
主要问题是:如果不使用JavaScript,是否可以实现这一目标?
.container {
display: flex;
width: 400px;
height: 2000px;
background-color: #aaa;
}
.left {
width: 150px;
background-color: lightgreen;
}
.right {
width: 100%;
background-color: lightcoral;
}
.fixed {
position: fixed;
height: 100px;
width: 100%;
background-color: skyblue;
}
<div class="container">
<div class="left">
My width can change anytime.
</div>
<div class="right">
<div class="fixed">
I'm fixed. Scroll the page to verify.<br /> I want to be the same width as my red parent.<br /> Any tips?
</div>
</div>
</div>
答案 0 :(得分:0)
您实际上可以根据弹性项目的宽度来计算所需的宽度。
左侧项目的宽度为150px,右侧项目的宽度为100%(解析为400px)。总计550像素,并且被压缩到400像素的flex容器中,因此右侧项目的实际使用宽度为400像素*(400/550)。
(当然,这是因为没有任何诸如弯曲增长之类的失真因素,这会使整个计算变得更加复杂!)
.container {
display: flex;
width: 400px;
height: 2000px;
background-color: #aaa;
}
.left {
width: 150px;
background-color: lightgreen;
}
.right {
width: 100%;
background-color: lightcoral;
position:relative;
}
.fixed {
position: fixed;
height: 100px;
background-color: skyblue;
width:calc(400px * (400 / (400 + 150)));
}
<div class="container">
<div class="left">
My width can change anytime.
</div>
<div class="right">
<div class="fixed">
I'm fixed. Scroll the page to verify.<br > I want to be the same width as my red parent.<br > Any tips?
</div>
</div>
</div>