我已经尝试了大约 6 种不同的方法,但都无法使它起作用。
我试图在使用 position:absolute;
此方法适用于所有浏览器,但如果缩小页面大小,底部会出现滚动条:
HTML:
<div class="wrapper">
<div class="header"></div>
<div class="footer"></div>
<div class="content">
<div class="content2">CENTER THIS DIV</div>
</div>
</div>
CSS:
div.header {
background:url('http://i.istockimg.com/file_thumbview_approve/11670843/2/stock-illustration-11670843-seamless-wallpaper-background-tile.jpg') top center repeat-x;
height:150px;
}
div.footer {
background:url('http://www.featurepics.com/FI/Thumb300/20081029/Blue-Tile-Background-947601.jpg') top left repeat-x;
height:150px;
}
div.content {
position:absolute;
top:20px;
left:50%;
height:250px;
width:300px;
}
div.content2 {
position:relative;
left:-50%;
background:white;
height:250px;
}
最佳答案
我建议使用这样的负边距:http://jsfiddle.net/joshnh/HFwMT/
调整后的代码如下:
HTML:
<div class="header"></div>
<div class="content">
<div class="content2">HERE</div>
</div>
<div class="footer"></div>
CSS:
.header {
background: url('http://i.istockimg.com/file_thumbview_approve/11670843/2/stock-illustration-11670843-seamless-wallpaper-background-tile.jpg') top center repeat-x;
height: 150px;
}
.footer {
background: url('http://www.featurepics.com/FI/Thumb300/20081029/Blue-Tile-Background-947601.jpg') top left repeat-x;
height: 150px;
}
.content2 {
background: #fff;
height: 250px;
left: 50%;
margin-left: -150px; /* Half of the width */
margin-top: -130px;
position: absolute;
width: 300px;
}
关于html - 没有负边距的绝对中心 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11554989/