Cross platform vertical align content in Section

时间:2015-08-07 02:33:31

标签: html css twitter-bootstrap cross-browser

I am attempting to vertically align (centre) all my content within a Section. My current CSS works only for Firefox and Chrome. It doesn't work on Safari or IE.

Can you suggest how I can vertically align the following that will work across Safari and IE (8+) aswell?

JSFiddle

<style>
html, body { 
    margin: 0; 
    padding: 0; 
    height: 100%; 
    width: 100%; 
}

section {
    min-height: 100%;
    width: 100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    vertical-align: middle;

    background-color: red;
}
</style>

<section>
    <div class="container vcenter">

        <h1> Some VCENTRED long long long long long long long long long text </h1>

    </div>
</section>

1 个答案:

答案 0 :(得分:1)

Add position relative to your section and also container, make your container display:inline-block to make sure it will not consume its vertical space, because div is set as block as default and we need inline-block, then finally make container margin:0 auto; to place it on the middle of the section.

html, body { 
    margin: 0; 
    padding: 0; 
    height: 100%; 
    width: 100%; 
}

section {
    min-height: 100%;
    width: 100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    vertical-align: middle;
    background-color: red;
    position:relative
}
.container
{
    display:inline-block;
    position:relative;
    margin:0 auto;

} 

Fiddle : https://jsfiddle.net/t7vudc77/1/

EDIT

put height:100% into your session, IE sometimes can't interpret min-height and put vertical-align:middle on container. updated fiddle: http://jsfiddle.net/t7vudc77/3/ I tested it in IE edge, unfortunately I use windows so I dont have safari.

section {
    min-height: 100%;
    height:100%;
    width: 100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    vertical-align: middle;
    background-color: red;
    position:relative
}
.container
{
    display:inline-block;
    position:relative;
    margin:0 auto;
    vertical-align:middle;
} 

This is used widely and commonly used by CSS dev, so I'm sure this is well supported in all major browser.