图片: 我有一个 container div(黄色),我想将其保持在窗口宽度的 50%。该容器的子容器是一个图像 div(紫色),它延伸到父容器宽度的 100%。在图像 div 的顶部有一个粘性标签(粉红色)(position:absolute因此它可以相对于图像偏移)。 我想保持整个屏幕的一半固定位置,以便在我滚动时保持粘性。
图像下方还有一个标题,无论是否垂直缩小窗口,该标题都必须可见。因此,在这种情况下,image div 应在需要时垂直收缩,以便显示该标题。
基本上我试图让图像 div 始终是父 容器 div 的 100% 宽度。图像 div 有一个 max % height 所以它可以垂直收缩。或者让它在垂直收缩时保持固定的纵横比(3:4 或其他)。
我试图避免在整个 CSS 中使用固定像素或 em。因为网站需要在垂直方向上有 flex/“流畅”,因为必须显示图片下方的标题。
HTML 大致如下:
<wrapper>
<left-column>
<normal text and scrollable stuff>
<right-column-yellow>
<image sticky label-pink>
<image div-purple>
<image title>
抱歉,如果这太令人困惑了,我的脑子快炸了!谁能帮帮我?
最佳答案
您可以使用固定位置来划分左右面板。
如果我的描述没有错,这就是答案。
<div class="wrapper">
<div class="left">
<p><!--Some very long text--></p>
</div>
<div class="right">
<div class="image">
<div class="label">Label</div>
<div class="title">Title</div>
</div>
</div>
一些CSS
.left,.right{
position: fixed;
width: 50%;
height: 100%;
display: inline-block;
}
.left{
left:0;
top: 0;
overflow: auto;
}
.right{
right: 0;
top:0;
background-color: yellow;
}
.right .image{
position: relative;
width: 100%;
height: 50%;
top: 50%;
left: 0;
background-color: #fff;
transform: translateY(-50%);
}
.right .image .label{
position: absolute;
left: 0;
right: 0;
top: -10px;
text-align: center;
width: 200px;
background-color: pink;
margin: auto;
}
.right .image .title{
position: absolute;
left: 0;
right: 0;
bottom: -40px;
text-align: center;
width: 200px;
background-color: #000;
margin: auto;
color: #fff;
font-size: 30px;
}
你也可以引用我的可待因。 https://codepen.io/masonwongcs/pen/WMJGZb
关于javascript - 基于 % 的固定和绝对定位的嵌套元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48897621/