html - 没有负边距的绝对中心 div

标签 html css

我已经尝试了大约 6 种不同的方法,但都无法使它起作用。

我试图在使用 position:absolute;

时将“div.content”在页面上水平居中

此方法适用于所有浏览器,但如果缩小页面大小,底部会出现滚动条:

http://jsfiddle.net/AuqXY/16/

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/

相关文章:

javascript - HTML +CSS +Javascript 编辑器

html - 嵌套 DIV 标签的 CSS

javascript - Bootstrap Navbar Active State Switching Bootstrap (Javascript相关)

css - Bootstrap 多列折叠

android - native 应用程序比 HTML5 更快

jquery - Html2canvas - 在phonegap应用程序中捕获谷歌地图到图像

css - 当存在继承类时,您可以使用 CSS 定位元素吗?

html - 如何将框阴影添加到容器内的 div? (包括图像)

twitter-bootstrap - Bootstrap 4 的媒体对象对齐(Flexbox)

html - 覆盖 dojo 内容 Pane 的全文 css 设置