简体   繁体   中英

Method for full-screen vertically-centered HTML page?

I'm looking for a valid cross-browser solution for an HTML page which:

  1. Consumes 100% of the screen height, with no overflow (ie no scrolling)
  2. has a vertically (and horizontally) centered <div> which will hold the main content

I know vertical centering is possible when the wrapping container has a static height. Is adjusting this height to browser window height something feasable? (Preferably, no JS should be used.)

Depends on what you mean with "cross browser". Following works fine with all current, standards compatible ones (thus not IE6):

HTML:

<div id="a">
    <div id="b">
        <div id="content"></div>
    </div>
</div>

CSS:

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

#a {
    display: table;
}

#b {
    display: table-cell;
    margin: 0;
    padding: 0;

    text-align: center;
    vertical-align: middle;
}

#content {
    border: 5px solid red;
    width: 100px;
    height: 100px;
    margin: auto;
}

Live example:

http://jsfiddle.net/mGPmr/1/

Is simply not possible without JavaScript, at least not with CSS2 or earlier (not sure if CSS3 makes this possible, someone clarify on that).

The other provided answers require absolute width and height for the element; I assumed no such requirement. There's no way to center a flowing element vertically which is what you usually want, given that you don't know the aspect ratio of the browser window to reliably use fixed-size containers for content.

You could do something like this. It looks to work in IE6 as well:

<html> <head>

<script type="text/javascript"> </script>

<style type="text/css">

#container {    height: 100%;   width: 100%;    position: relative; }


#content {
    border: 5px solid red;
    width: 100px;
    height: 100px;
    position: relative;
    margin-left: -50px;
    margin-right: -50px;
    top: 50%;
    left: 50%; }


</style>


</head> <body>

<div id="container">
        <div id="content"></div> </div>

</body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM