Vertical Centering in CSS

Yuhu's Definitive Solution with Unknown Height

Though there is a CSS property vertical-align, it doesn't work like attribute valign in HTML tables. CSS property vertical-align doesn't seem to be able to solely solve this problem:

Definition of the problem

there is an area (e.g. <div>) with known height in the page

an internal object (typically long text in <div>) is inside the area and I don't know its height (e.g. because its content is dynamically generated from a database)

(e.g. because its content is dynamically generated from a database) I want to center the object vertically within the area

within the area without using HTML tables.

No general solution was known until September 2004. I have found it going home on Wilson street.

Display an example of the vertical centering in your browser.

Update 2015 - flex

As new browsers support display: flex, it is much easier to vertical center an item with CSS than before.

<style>

#containter {

height: 400px;

display: flex;

/* flex-direction: column;*/

align-items: center;

/* justify-content: center;*/

}

#content {}

</style>



<div id=" containter ">

<div id=" content ">

any text<br>

any height<br>

any content, for example generated from DB<br>

everything is vertically centered

</div>

</div>

See this example in browser.

Uncommenting justify-content: center or flex-direction: column you can get other types of centering (horizontal, both). For instance justify-content: center with align-items: center leads to centered content both vertically and horizontally.

The most important rule is display: flex . This relatively new value switches the display of the containter to a special mode, enabling its direct descendant to use and align in all the space of the containter (using special properties like align-items and others). The container has set some width, i.e. width: 400px just for purpose of this example. There is no need to style the content element, but it must be direct descendant of the container.

Support of display: flex is very good in modern browsers. Last not-supporting browsers are Internet Explorer 9 and 10 (version 10 has a special syntax of flex). If it is important for you to optimize for those and older browsers, you should read the rest of this page.

Original content from 2004 with updates:

The idea

The keystone of the solution for Internet Explorer 6, 7 or quirk mode is this: the internal object is absolutely positioned in half of the area height. Then is moved up by half of its height. The wrong interpretation of the height property in older Internet Explorer is used as a feature here (counted height is taken as a base of percentage height of nested tags). One extra nested tag <div> is needed for those Explorers.

Solution for standard browsers like Mozilla, Opera, Safari etc. (including IE 8, 9, 10 and younger) is completely different. Entire area (top <div>) is set to be displayed as a table (display: table; part of CSS2). The internal object is set as table-cell (display: table-cell). Now -- there is the key idea -- it is possible to use vertical-align property for such table-displayed element in standard browsers. (Internet Exlorer 6, 7 and quirk mode ignores those properties or doesn't know their values.)

Then both syntax are merged. I use the Pixy's underscore hack, but with sign #. A CSS property written with the char # on the start (i.e. #position) is visible for IE 7 and older. Such written property is invisible for any other standard browser (e.g. Explorer 6 or 7 interprets #position: absolute; unlike other browsers). This so called "underscore hack" seems to be valid, but if you don't want to use it, you may use the more structured code below in my second example (unfortunately, not working for IE 7). Other types of browsers and Internet Explorer 8 and younger don't need to be hacked, as they support display: table-cell properly.

Compatibility

The code below works in Internet Explorer 5.0, 5.5, 6.0, 7, 8, 9 and 10 beta, in Gecko browsers (Mozilla, Firefox, Netscape 7), in Opera 7, 8 and up, every Chrome, Konqueror 3.3.1. (maybe lower too), and in Safari (Win, iOS). The page can be HTML, HTML5 or XHTML, standard or quirk mode.

The valid example doesn't work in IE 7 standard mode (update 2012: about 3 % of clients). If you find any easy workaround for IE 7, please let me know.

Understandable code:

<!DOCTYPE HTML>

<html>

<head>

<title>Universal vertical center with CSS</title>

<style>

.greenBorder {border: 1px solid green;} /* just borders to see it */

</style>

</head>



<body>

<div class="greenBorder" style=" display: table ; height: 400px; #position: relative; overflow: hidden; ">

<div style=" #position: absolute; #top: 50%; display: table-cell; vertical-align: middle; ">

<div class="greenBorder" style=" #position: relative; #top: -50% ">

any text<br>

any height<br>

any content, for example generated from DB<br>

everything is vertically centered

</div>

</div>

</div>

</body>

</html>

See this example in browser

Legend for colors:

CSS styles for every browser

CSS styles for standard browsers

CSS style only for Internet Explorer 6, 7 and quirk (with # hack)

The result looks:

any text

any height

any content, for example generated from DB

everything is vertically centered

See this example in browser

Let's make it structural and without hacks

(NOTE: this valid solution described below doesn't work in Internet Explorer 7 (standard mode), because IE7 doesn't understand table- values in display property. The centered object is too high. BUT: IE 7 is used by only about 3 % of users (2012) and the number will decrease. If you still do mind IE7 users, please use the non-valid solution above, write in quirk mode, or use html conditional comments for separating the properties for IE 7 somehow.)

The first example above is not nice, but I hope you have understood it. It's possible to write code differently. For example this way:

<div id=" outer ">

<div id=" middle ">

<div id=" inner ">

any text

any height

any content, for example generated from DB

everything is vertically centered

</div>

</div>

</div>

And the structured valid style:

<style type="text/css">

#outer {height: 400px; overflow: hidden; position: relative; }

#outer[id] {display: table; position: static;}



#middle {position: absolute; top: 50%;} /* for quirk explorer only*/

#middle[id] {display: table-cell; vertical-align: middle; width: 100%; position: static;}



#inner {position: relative; top: -50%} /* for quirk explorer only */

/* optional: #inner[id] {position: static;} */

</style>

See the valid example in browser (it looks the same way as the last one).

Color legend:

CSS style for Internet Explorer 6 only (or quirk)

CSS styles for standard browsers

CSS2 selector #value[id] is equivalent to selector #value , but Internet Explorer 6 ignores these types of selectors with [id]. Generally: syntax *[foo] means any element with attribute foo . Any HTML element #something must have the attribute id by definition set to "something". That's the trick -- #value[id] works in standard browsers only (similarly works .value[class])

There's CSS property position set to absolute or relative for Internet Explorer. The code position: static get's it back to default value in standard browsers (property top doesn't work then).

Both vertical and horizontal centering

The core code will be the same, you just need to add some extra CSS rules. If is your page in standard mode, add this code:

<style>

#outer {width: 100%;}

#inner {width: 200px; margin-left: auto; margin-right: auto;}

</style>

As you probably see, this is the most common horizontal centering method - auto left and right margin. Because margins needs the space in Firefox and Opera, you need to set a width to the #outer div. If 100% doesn't fit your needs, use any other value.

The important thing is to set some proper width to #inner. This tutorial is about vertical centering of an object with unknown height. I assume that you know the width of the object (in most cases you will simply decide how wide it should be). You may use the pixel values, or the percentage width. If the centered object is only an unknown-size image, you don't need to set width.

If you use quirk mode page rendering (mode depends on !Doctype, as you know), added code should be a bit longer, because quirk mode of Exploder doesn't understand auto margins, but has one nice bug in text-align interpretation instead. This code should work for both standard and quirk mode:

<style>

#outer {width: 100%;}

#middle {width: 100%; text-align: center;}

#inner {width: 200px; margin-left: auto; margin-right: auto; text-align: left;}

</style>

Please take note that this is just part of code, which you have to add to the previous example. If you are lazy to combine codes, please see the complete example in browser: vertical and horizontal centering. You know, I'm lazy too.

How to center vertically on window's height

The same way, and just add the style:

<style>

body, html {height: 100%;}

#outer {height: 100%; overflow: visible;} /* or without overflow */

...

</style>

It seems that #outer declaration should be sufficient, but it is not. Body and html declaration sets 100% of the window's height as a base for next percentage. Now it is better not to set overflow: hidden (like in the examples above), because when the content would be taller than window, then it would be impossible to scroll on.

Related

Previous attempt to center vertically:

Examples:

Read in other language:

Centralizando verticalmente com CSS - Brazilian Portuguese translation of this article by Maurício Samy Silva

Вертикальне центрування в CSS - Ukrainian translation by Agnessa Petrova from A2Goos team

Вертикальное центрирование в CSS - Russian translation by Aleksandr Molochan

Czech version of this article (original, not updated)

All other articles on this website www.jakpsatweb.cz is in Czech.

About

First published Sep 21, 2004, updated Oct 23, 2006 and May 25 2008. Major update Dec 6 2012 including bugfix of code in valid example. June 2015 major update about flex. I'll update this article with more information if you wish.

Author:

Dušan Janovský

aka Yuhů

janovsky@gmail.com

www.jakpsatweb.cz

From Prague, Czech Republic, search algorithms specialist in Seznam.cz search engine. Wi Tw Fb