我多次遇到这个问题,我决定问一下。当我使用相对定位时width:100%
,内容不会从屏幕边缘延伸到边缘。另一方面,当我使用绝对或固定定位时,内容确实会从边到边。为什么是这样?这是一个示例代码来显示我的问题:
#container {
display: block;
width: 100%;
position: relative;
height: 150px;
border: 1px solid;
text-align: center;
}
<div id='container'>
<br />
<br />^
<br />
<- Why do I have these spaces? ->
<br />\/
</div>
Result:
What I want:
在谷歌搜索时,我确实遇到了这一页 https://stackoverflow.com/questions/18520625/css-trying-to-use-width100-to-make-a-table-expand-relative-to-window-size-cre,但看起来这个问题是由于没有申请造成的text-align: center
.
你必须重置默认值body
边距/填充。
box-sizing: border-box;
还有助于将边框尺寸纳入宽度计算中。
body {
margin: 0;
padding: 0;
}
#container {
display: block;
width: 100%;
position: relative;
height: 150px;
border: 1px solid;
text-align: center;
box-sizing: border-box;
}
<div id='container'>
<br />
<br />^
<br />
<- Why do I have these spaces? ->
<br />\/
</div>
参考:body典型的默认显示属性 http://www.w3.org/TR/html-markup/body.html#body-display - 盒子尺寸 https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)