有固定位置div可以继承父级宽度的方法吗?
我知道固定宽度是相对于窗口的宽度,因此此代码不起作用:
#wrapper{
position: relative;
width:500px;
height: 20px;
background-color: blue;
}
#header{
position: fixed;
width: 100%;
height: 20px;
background-color: rgba(255,0,0,0.5);
}
<div id="wrapper">
#wrapper
<div id="header">
#header
</div>
</div>
使用选择器上属性的inherit
值。width
#header
为什么这样有效
通过指定position: fixed
到#header
元件,所述#header
元件的位置被计算相对于如在CSS2规范指定的视口:
http://www.w3.org/TR/2011/REC-CSS2-20110607/visuren.html#positioning-scheme
但是,position: fixed
不会更改DOM结构,这意味着该#wrapper
元素仍然是该#header
元素的父级。结果,#header
即使相对于视口确定了其位置,仍然可以从其父元素继承属性值。
还请注意,如果您为宽度指定百分比值,则固定元素将根据规格中的视口计算该值。但是,这与无关width: inherit
,它从父元素而不是视口获取其值。
参见:http : //www.w3.org/TR/2011/REC-CSS2-20110607/visudet.html#propdef-width
例如,如果将color
属性添加到#wrapper
,它将被继承#header
。
区别在于的初始值/默认值width
是,auto
而forcolor
则是inherit
。要获取父项的with属性,您需要指定width: inherit
,而不是width: 100%
;
注意:父元素和包含块之间有细微的区别。在大多数情况下,两者是相同的,但是对于固定位置的元素,它们是不同的。
#wrapper {
position: relative;
width: 500px;
height: 20px;
background-color: blue;
color: white; /* for demo */
}
#header {
position: fixed;
width: inherit;
height: 20px;
background-color: rgba(255, 0, 0, 0.5);
}
<div id="wrapper">
#wrapper
<div id="header">
#header
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句