vertically center div when body height: 100% without absolute pos

余生长醉 提交于 2019-12-04 13:42:14

问题


I have this to fill the window:

html, body {
height: 100%;}

then a container also set to height: 100%, how do I vertically center a div with an image without specifying and set height in pixels and without using absolute positioning? Using padding-top: 50%; padding-bottom 50%; isn't working - seems to shift the div depending on device site or browser window.


回答1:


You can use display:table and display: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

More on display property .




回答2:


today, display:table and table-cell make it easy, you can have tags to react as a <table> would. basicly :

html, body {
    height: 100%;
    width: 100%;
    margin: 0;
}
html {
    display: table;
}
body {
    display: table-cell;
    vertical-align: middle;
}

whatever will be in body will be vertical-align in the middle. for text a small box , use text-align on body or margin : auto. you can transfer display to body and div instead html and body.



来源:https://stackoverflow.com/questions/21241800/vertically-center-div-when-body-height-100-without-absolute-pos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!