css - 当 body 高度为 : 100% without absolute pos 时垂直居中 div

标签 css vertical-alignment

我有这个来填充窗口:

html, body {
height: 100%;}

然后容器也设置为 height: 100%,如何在不指定和设置像素高度的情况下将带有图像的 div 垂直居中,并且使用绝对定位?使用 padding-top: 50%;底部填充 50%;不工作 - 似乎根据设备站点或浏览器窗口移动 div。

最佳答案

您可以使用 display:tabledisplay:table-cell:

html, body {
    width: 100%;
    height: 100%;
}

body{
    margin: 0;
    display: table
}

body>div {
    display: table-cell; 
    text-align: center; /* horizontal */
    vertical-align: middle; /* vertical */
}
<div>
    <img src="http://paw.princeton.edu/issues/2012/07/11/pages/6994/C-beer.jpg" />
</div>

JSFiddle

更多关于 display property .

关于css - 当 body 高度为 : 100% without absolute pos 时垂直居中 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21241800/

相关文章:

html - 淡出顶部的图像

javascript - 选择下拉菜单中的新选择时,将 CSS 类还原为原始类

html - CSS : how to center a input inside a div

html - CSS垂直对齐和 float 问题

html - 为什么垂直对齐是:middle not aligning things in my table row?

javascript - Nanoscroll 不支持多内容

css - 嵌套在 <p> 元素内的 <a> 元素的填充问题

css - 如何使用 YUI 网格垂直定位 div?

twitter-bootstrap - 如何在 Bootstrap 4 中垂直对齐导航栏切换器?

html - 固定 block 元素