我经常遇到这个问题,我需要内部容器的宽度(比如设置宽度为 960px 的 wrapper )来跨越 100% 的宽度,但我无法触及 html,所以它必须全部通过 CSS 完成。
我知道我可以定位:绝对;那个家伙把他从 wrapper 中取出来...但是还有另一种...更好的方法吗?
这里有一个 JsFiddle 链接,有助于使其更清晰:
<!-- html -->
<div id="container">
<div id="inner-container"></div>
</div>
<!-- CSS -->
#container {
width: 500px;
height: 500px;
background: gray;
margin: auto;
}
/* here's the container that I want to be 100% */
#inner-container {
width: 100%; /* :( */
height: 100px;
background: black;
}
编辑:
这是一个带有我的绝对定位版本的 jsFiddle...我想知道是否可以在没有绝对定位的情况下完成
<div id="container2">
<div id="inner-container2">
</div>
#container2 {
width: 500px;
height: 500px;
background: gray;
margin: auto;
clear: both;
margin-top: 20px;
}
#inner-container2 {
background: black;
width: 100%;
height: 100px;
position: absolute;
left: 0;
}
最佳答案
还有另一种方法。
主体 -> 容器 -> 子级
现在,正如标题所暗示的那样,这种方式将其宽度传递给容器,然后从容器传递给它的子容器。这样 child 就可以得到 body 的总宽度。
解释
您在这里面临的唯一问题是静态宽度不会保持 <body>
记住宽度(又名视口(viewport))。所以你必须使用百分比值作为宽度,这样它将基于 <body>
:
#container {
/*width: 500px;*/
width: 70%;
height: 500px;
background: gray;
margin: auto;
}
现在 child 知道它的 parent (#container
)的宽度是整个 body 的 70%。
然而,100% 的宽度只会得到 <body>
的 70%。宽度。相反,您需要 100% + 70% 中的 30%。 70% 的 30% 等于 42%(35% 就是 50%)。
现在我们得到了 <body>
的 100% .现在你可以让它看起来像是在容器宽度之外的负边距。为了使它居中,您希望它减去您刚刚计算的 42%(= body 的 30%)的一半:
#inner-container {
/*width: 100%; /* :( */
width: 142%;
margin-left: -21%;
height: 100px;
background: black;
}
jsFiddle
但是,这样好用吗?
嗯,这是对您问题的回答。不使用 position: absolute
是可能的.
绝对位置会更容易吗?
绝对是:
#inner-container {
width: 100%; /* :( */
height: 100px;
background: black;
position: absolute;
left: 0;
}
只有两行代码,没有任何计算:)
jsFiddle
关于css - 在其设置宽度的父容器之外打破 div 的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20676443/