【问题标题】:vertically centered image in divdiv中垂直居中的图像
【发布时间】:2014-08-27 02:00:08
【问题描述】:

我尝试将图像垂直居中放在身体中间,但似乎没有任何效果。我尝试过在这里找到的不同技巧(高度 100%、表格单元格、位置:相对...),但直到现在都没有运气。我的代码是 html:

 <div id="container">
   <div id="header">Header</div>
   <div id="body">
       <div class="image"></div>
   </div>
   <div id="footer">Footer</div>
 </div>

CSS:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
#container {
   min-height:100%;
   position:relative;
}
#header {
   background:#ccc;
   padding:10px;
}
#body {
   padding:10px;
   padding-bottom:60px;
}
.image {
    background: url("http://lorempixel.com/300/200/nature/") no-repeat center;
    height: 200px;
    width: 100%;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
   background:#ccc;
}

我在这里做了一个小提琴:http://jsfiddle.net/dragoeco/hjcz6j0r/1/ 我正在寻找一个使用 IE8+ 的工作解决方案,所以也许有一种 jQuery 方法来完成这项工作?对我来说重要的是将页脚保持在视口底部,这就是为什么我为页脚使用绝对位置的原因。谢谢。

【问题讨论】:

标签: html css background-image vertical-alignment


【解决方案1】:

可能是这样的:

LIVE EXAMPLE

html, body {
    height: 100%;
}
#container {
    height: 100%;
    width: 100%;
    display: table;
    margin-top:-60px; //height of the footer
}
#body {
    display: table-cell;
    height: 100%;
    vertical-align: middle;

}

.image {
    background: url("http://lorempixel.com/300/200/nature/") no-repeat center;
    height:200px;
}

#header {
   background:#ccc;
   padding:10px;
}

#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
   background:#ccc;
}

【讨论】:

  • 谢谢,这很好用。但我在谢尔盖解决方案和你的解决方案之间犹豫不决。您认为哪个更好:表格单元格还是绝对位置?我的意思是,跨浏览器兼容性有区别吗?
  • @dragoeco 我不使用绝对位置,我的解决方案来自 CSS Tricks。 css-tricks.com/centering-in-the-unknown 。所以我觉得我的解决方案更好,但我不想自大
【解决方案2】:

我使用以下 CSS 取得了成功:

html,
body {
   margin:0;
   padding:0;
   height:100%;
}
#container {
   min-height:100%;
   position:relative;
}
#header {
   background:#ccc;
   padding:10px;
   position: relative;
}
#body {
   padding:10px;
   padding-bottom:60px;
    position: relative;
}
.image {
    background: url("http://lorempixel.com/300/200/nature/") no-repeat center ;
    position: absolute;
    height: 200px;
    width: 100%;
    top: 50%;
}
#footer {
   position:absolute;
   bottom:0;
   width:100%;
   height:60px;
   background:#ccc;
}

来源:http://www.w3.org/Style/Examples/007/center.en.html#vertical

【讨论】:

    【解决方案3】:

    添加这个:

    .image{
        position: absolute;
        top: 50%;
        margin-top: -100px;
    }
    

    它适用于任何地方(除了 IE6-7,那里可能需要相对位置)。您可以对水平居中执行相同的操作。

    这里是小提琴:http://jsfiddle.net/hjcz6j0r/7/

    【讨论】:

    • 到目前为止,这里提出的所有建议都运行良好,但这是一种优雅而简单的方法。谢谢谢尔盖
    • 不客气。在我看来,最简单的解决方案是最好的。为了跨浏览器的兼容性,所有浏览器都支持负边距(只是有时在 IE6 和 7 中不起作用,定位相对修复它)。