CSS:不使用position:absolute将内部div的宽度设为100%-可以吗? [英] CSS: Make inner div 100% body width without using position:absolute - is it possible?
问题描述
让我们假设由于某种原因我无法更改HTML,也没有使用JavasScript。假设 #content_actual
的位置取决于 #element
的高度。 #element
具有灵活的高度。
Lets assume for some reason I can not change the HTML, neither use JavasScript. Lets assume the position of #content_actual
depends on the height of #element
. #element
has a flexible height.
是否可以解决此问题?
HTML:
<div id="content">
<div id="element">ABCDE</div>
<div id="content_actual">FGHIJ</div>
</div>
CSS:
#content {
width:960px;
margin: 0 auto;
}
#element {
// width: 100% of body width
// position: everything but position absolute or fixed
}
推荐答案
相对位置,视口单位和<$ c $的组合c> calc 。
A combination of relative positioning, viewport units and calc
.
注意:只要视口小于容器的宽度。此时需要媒体查询。
NOTE: this breaks as soon as the viewport is less than the container width. Media queries would be required at that point.
#content {
width: 480px; /* numbers changed for this Snippet */
margin: 0 auto;
background: green;
padding: 50px;
}
#element {
height: 50px;
line-height: 50px;
width: 100vw;
position: relative;
right: calc(50vw - 240px); /* second value 50% of container width */
background: lightblue;
}
<div id="content">
<div id="element">ABCDE</div>
<div id="content_actual">FGHIJ</div>
</div>
还应注意,容器不能具有 overflow:hidden
才能使此技术起作用。
It should also be noted that the container cannot have overflow:hidden
for this technique to work.
这篇关于CSS:不使用position:absolute将内部div的宽度设为100%-可以吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!