简体   繁体   English

如何使固定定位的 div 使用其父级的 rest 宽度?

[英]How to make a fixed positioned div use the rest width of its parent?

I have 2 columns in a container (whose width dynamically changes in our situation).在一个容器中有 2 列(其宽度在我们的情况下动态变化)。 The left-column (green) has always a fix width of ie 100px, and flows with the document as usual.左列(绿色)始终具有固定宽度,即 100 像素,并像往常一样随文档流动。 The right column (blue) has a position: fixed , because i have a JS code, which sets the top&bottom positions of this right column dependent on the scroll position.右列(蓝色)有一个 position: fixed ,因为我有一个 JS 代码,它根据滚动 position 设置此右列的顶部和底部位置。

I want that my fixed positioned right column does not expand its parent on the X axis, but just use the space left from the left-column .我希望我的固定定位右列不会在 X 轴上扩展其父级,而只是使用 left-column 留下的空间 Is it possible?可能吗?

Now i have width:inherit, which actually makes the whole right-column having the same width as its parent.现在我有了 width:inherit,它实际上使整个右列的宽度与其父级相同。 But i have to substract the width of the left-column from this width, so that the right-column does not expand the container.但是我必须从这个宽度中减去左列的宽度,这样右列就不会扩展容器。

Here is a fiddle for a simplified version of my problem:这是我的问题的简化版本的小提琴:

http://jsfiddle.net/gj4a5hde/ http://jsfiddle.net/gj4a5hde/

在此处输入图像描述

 .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>

Set the parent .container to have transform: translate(0,0) .将父.container设置为具有transform: translate(0,0) This will make the fixed element "fixed" to the parent instead of the viewport.这将使固定元素“固定”到父元素而不是视口。 Then use calc(100% - 110px) to set the width of your fixed element.然后使用calc(100% - 110px)设置固定元素的宽度。 That will take the margin into account and remove it from the overall width of the fixed element.这将考虑margin并将其从固定元素的整体宽度中删除。

You will need to adjust the top value to what you want.您需要将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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM