Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering page content vertically

Tags:

html

css

I know how I can horizontally center the entire page with CSS. But is there a way to vertically center the page? Something like this...


Example


like image 600
Pieter Avatar asked Mar 12 '11 13:03

Pieter


People also ask

How do I center the contents of a div vertically?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.


1 Answers

You can also hijack CSS's display: table and display: table-cell for this purpose. The HTML would be like this:

<body>
    <div id="body">
        <!-- Content goes here -->
    </div>
</body>

And the CSS:

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

If you want horizontal centering as well, then add this:

#body {
    max-width: 1000px; /* Or whatever makes sense for you. */
    margin: 0 auto;
}

Some would call this an abuse of CSS but:

  • It will work exactly the same pretty much everywhere.
  • Requires minimal markup and styling.
  • And CSS's vertical alignment deserves a bit of abuse; vertical alignment shouldn't require the hacking, contortions, and absolute sizing that it does.

References:

  • Flexible height vertical centering with CSS, beyond IE7
  • Wolf in Sheep’s Clothing
like image 75
mu is too short Avatar answered Sep 18 '22 14:09

mu is too short