我在%宽度容器中有一个固定的div。
HTML:
<div class="master-container">
<div class="container">
<div class="fixed">
</div>
</div>
</div>CSS:
.master-container {
max-width: 1200px;
margin: 0 auto;
}
.container {
width: 30%;
}
.fixed {
position: fixed;
}我看过其他几篇文章:
一般的答案是在固定元素上设置width: inherit。问题是它仍然继承来自主体的宽度,而不是它的百分比(除非我在父服务器上设置了一个固定的宽度)。
因此,当父级宽度设置为百分比时,如何将固定的div大小设置为它的直接父级。
我只是在寻找CSS的解决方案--它是可能的还是我必须要JS的?
编辑
到目前为止,大多数解决方案都继承了页面的宽度,在这个页面中,我需要得到固定的div来占据中心中心的30%的容器,即中心的网页,它的最大宽度为1200 max。
发布于 2017-09-15 13:15:08
如果您的父div与身体的宽度相同,这个“工作”很好。当然,它只是在外表上起作用,而不是在现实中。这个div占浏览器宽度的30%,就像它的父div一样。
html, body {
margin: 0;
}
.container {
width: 30%;
height: 400px;
background: linear-gradient(green, white)
}
.fixed {
position: fixed;
background: red;
width: inherit;
height: 10px;
}<div class="container">
<div class="fixed"></div>
</div>
否则,要在CSS中实现这一点,您可以根据您的结构选择几个选项。
根据您的问题,我们知道fixed div的直接父级有一个百分比宽度(我们将使用30%)。该.container div必须有一个或多个具有以下属性的父div:
这将(可能)计算在CSS中。否则,我不知道为什么你会想要一个CSS唯一的解决方案。
因此,如果您有一个宽度为500px的容器div的父级,则可以将fixed div设置为与.container相同的宽度,方法是给它30%的500 30:
html, body {
margin: 0;
}
.parent {
width: 500px;
height: 400px;
background: linear-gradient(blue, white)
}
.container {
width: 30%;
height: 400px;
background: linear-gradient(green, white)
}
.fixed {
position: fixed;
background: red;
width: calc(500px * .3);
height: 10px;
}<div class="parent">
<div class="container">
<div class="fixed"></div>
</div>
</div>
如果.parent div在%或vw中有一个宽度,或者其他任何东西,这也是可行的:
html, body {
margin: 0;
}
.parent {
width: 50%;
height: 400px;
background: linear-gradient(blue, white)
}
.container {
width: 30%;
height: 400px;
background: linear-gradient(green, white)
}
.fixed {
position: fixed;
background: red;
width: calc(50% * .3);
height: 10px;
}<div class="parent">
<div class="container">
<div class="fixed"></div>
</div>
</div>
显然,您必须知道所有父母的宽度,直到身体或最近的div与一个固定的宽度,并在CSS calc中做数学调整。但是,如果没有JS,并且所有父div宽度都是在CSS中定义的,则可以这样做。
编辑:基于您更新的问题的:
html, body {
margin: 0;
}
.master-container {
width: 100%;
max-width: 1200px;
margin: 0 auto;
background: linear-gradient(blue, white)
}
.container {
width: 30%;
height: 400px;
background: linear-gradient(green, white)
}
.fixed {
position: fixed;
background: red;
width: calc(1200px * .3);
height: 10px;
}
@media (max-width: 1200px) {
.fixed {
width: 30%;
}
}<div class="master-container">
<div class="container">
<div class="fixed"></div>
</div>
</div>
发布于 2017-09-15 12:50:35
您可以使用width: inherit;实现这一点。
.container {
width: 30%;
background: #444;
height: 50px;
}
.fixed {
width: inherit;
height: 40px;
position: fixed;
background: #ccc;
}<div class="container">
<div class="fixed">
</div>
</div>
您也可以检查小提琴
发布于 2017-09-15 13:24:34
你不能用百分比的宽度来做这件事。一旦您固定了一个元素,它的大小和位置属性就会变得相对于视口,而不是父元素。它实际上是它的父堆叠上下文的“突破”,并成为一个新的CSS属性,所以即使CSS属性仍然可以被继承,它的计算方式也完全不同。
您唯一的选择是使用以像素为单位的固定宽度,并在必要时使用JS同步两者。
https://stackoverflow.com/questions/46239029
复制相似问题