我在一个容器中有 2 列(其宽度在我们的情况下会动态变化)。 左栏(绿色)始终具有固定宽度,即 100 像素,并像往常一样随文档流动。 右栏(蓝色)有一个位置:fixed,因为我有一个JS代码,它根据滚动位置设置了右栏的顶部和底部位置。
我希望我的固定定位的右列不会在 X 轴上扩展其父列,而只是使用左列左侧的空间。可能吗?
现在我有了 width:inherit,这实际上使整个右列与其父列具有相同的宽度。但是我必须从这个宽度中减去左列的宽度,这样右列就不会扩展容器。
这是我问题的简化版本的小提琴:
.container {
margin-top: 30px;
height: 1400px;
width: 600px;
background-color: lightgray;
border: 2px solid black;
}
.left-column {
height: 1200px;
width: 100px;
background-color: green;
}
.right-column {
position: fixed;
top: 50px;
margin-left: 110px; /* always fix, since the width of the left-column does not change */
height: 200px;
width: inherit;
max-width: inherit;
background-color: blue;
}
<div class="container">
<div class="left-column"></div>
<div class="right-column"></div>
</div>
答案 0 :(得分:1)
将父 .container
设置为具有 transform: translate(0,0)
。这将使固定元素“固定”到父元素而不是视口。然后使用 calc(100% - 110px)
设置固定元素的宽度。这将考虑 margin
并将其从固定元素的总宽度中删除。
您需要将 top
值调整为您想要的值。
.container {
margin-top: 30px;
height: 1400px;
width: 600px;
background-color: lightgray;
border: 2px solid black;
transform: translate(0,0);
}
.left-column {
height: 1200px;
width: 100px;
background-color: green;
}
.right-column {
position: fixed;
top: 50px;
margin-left: 110px; /* always fix, since the width of the left-column does not change */
height: 200px;
width: calc(100% - 110px);
max-width: inherit;
background-color: blue;
}
<div class="container">
<div class="left-column"></div>
<div class="right-column"></div>
</div>