892

I have a div with two images and an h1. All of them need to be vertically aligned within the div, next to each other.

One of the images needs to be absolute positioned within the div.

What is the CSS needed for this to work on all common browsers?

<div id="header">
  <img src=".." ></img>
  <h1>testing...</h1>
  <img src="..."></img>
</div>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Abdu
  • 14,323
  • 12
  • 56
  • 82

28 Answers28

1012

Wow, this problem is popular. It's based on a misunderstanding in the vertical-align property. This excellent article explains it:

Understanding vertical-align, or "How (Not) To Vertically Center Content" by Gavin Kistner.

“How to center in CSS” is a great web tool which helps to find the necessary CSS centering attributes for different situations.


In a nutshell (and to prevent link rot):

  • Inline elements (and only inline elements) can be vertically aligned in their context via vertical-align: middle. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. jsfiddle example
  • For block elements, vertical alignment is harder and strongly depends on the specific situation:
    • If the inner element can have a fixed height, you can make its position absolute and specify its height, margin-top and top position. jsfiddle example
    • If the centered element consists of a single line and its parent height is fixed you can simply set the container’s line-height to fill its height. This method is quite versatile in my experience. jsfiddle example
    • … there are more such special cases.
Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
  • 164
    The problem with the "valid" solutions (so not the `vertical-align: middle`) is that you have to specify a fixed height. Not very possible for _Responsive Web Design_. – Emilie May 14 '13 at 08:42
  • 1
    I had this structure:
    My Text div> Worked for me set the property lineHeight using the same value as used in div height property: '##px' (## because this value is dynamic in my case) thank you
    – patricK Aug 24 '13 at 20:00
  • 8
    This also works with `inline-block` and `table-cell` elements. If you are having issues with this, try adjusting `line-height` of the container element (i.e. context) since it is used in the `vertical-align` line box calculations. – Alex W Oct 16 '13 at 19:14
  • 2
    https://css-tricks.com/centering-css-complete-guide/ – shaunhusain Feb 21 '16 at 01:20
  • [Understanding vertical-align, or "How (Not) To Vertically Center Content](http://phrogz.net/CSS/vertical-align/index.html) could have done better with the latest standards. All modern browsers now support `transform: translateY(-50%)` (although you still have to add the prefix like `webkit`, `mz` etc). Using this instead of `margin-top: -yy` would be a better fit. – Meliodas Apr 26 '17 at 12:28
  • @DazzleR “Understanding vertical-align, or "How (Not) To Vertically Center Content” predates the latest standard (rather, its adoption) by more than a decade. ;-) — I’d add it, but other answers already include it. – Konrad Rudolph Apr 26 '17 at 15:07
  • @KonradRudolph There is no denying that it predates even my puberty! :-P It is just that things will be much easier for newbies if green ticked answer would contain answer with updated standards, don't you think? – Meliodas Apr 27 '17 at 20:34
  • The options listed on the link don't work if your inner element is an image. http://jsfiddle.net/rhvqd52c/ – Gaurav Jain Aug 05 '17 at 23:20
  • @GauravJain Sure does: make it `inline` and give it `vertical-align: middle`, *or* keep it `block` and set its `margin-top`. Your example is mixing block-level and inline-level alignment hints. `` isn’t special in any way, it behaves like any other element here. – Konrad Rudolph Aug 07 '17 at 09:56
  • “How to center in CSS” is a great web tool indeed. 10x – benshabatnoam Oct 16 '18 at 06:34
  • 1
    This tool (howtocenterincsss.com) is pretty awesome because it worked right out of the box _inside_ my existing CSS! That is super rare. Remember the old days where you had to copy entire stylesheets from some example, sometimes even the example HTML an then remove and rename elements one after each other until it's what I needed. Not the case for this site! – konstantin Apr 04 '20 at 13:46
259

Now that Flexbox support is increasing, this CSS applied to the containing element would vertically center the contained item:

.container {
    display: flex;
    align-items: center;
}

Use the prefixed version if you also need to target Internet Explorer 10, and older (< 4.4 (KitKat)) Android browsers:

.container {
    display: -ms-flexbox;
      display: -webkit-flex;
    display: flex;

       -ms-flex-align: center;
    -webkit-align-items: center;
       -webkit-box-align: center;

       align-items: center;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
E. Serrano
  • 3,717
  • 1
  • 14
  • 14
  • A nice solution, thank you. Can you suggest how to make flexbox display a horizontal scrollbar, in case the inner element is bigger than the container? (I'm trying to make inner element zoomable/scrollable within the container, like canvas in powerpoint)? Is it possible at all? – Boris Burkov Nov 04 '15 at 05:18
  • 1
    @YazidErman this solution depends on flexbox so no, only IE 10 and above support or any other modern browser http://caniuse.com/#search=flexbox Flexbox is great where it's supported but that's not everywhere. The display table and table cell is probably the best solution really, container just needs to be table, element being centered is wrapped an element with display table cell then can just center as some other answers here point out. – shaunhusain Feb 21 '16 at 01:16
  • 1
    Why was this so hard for me to find >.< thanks for the answer! Can confirm this is working for me in a scenario where other answer did not work. – Michael McKenna Apr 30 '19 at 20:43
  • 1
    Useful [CSS tricks guide on flexbox](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) then look at the `align-items` section – icc97 May 21 '19 at 10:06
  • Just what I needed. – Carlos López Marí Aug 05 '19 at 12:25
  • 1
    In 2020 we can use flexbox caniuse.com/#feat=flexbox – tonygatta Jan 31 '20 at 11:09
  • good........... – Cloud Feb 28 '21 at 17:48
125

I used this very simple code:

HTML:

<div class="ext-box">
    <div class="int-box">
        <h2>Some txt</h2>
        <p>bla bla bla</p>
    </div>
</div>

CSS:

div.ext-box { display: table; width:100%;}
div.int-box { display: table-cell; vertical-align: middle; }

Obviously, whether you use a .class or an #id, the result won't change.

johannchopin
  • 7,327
  • 6
  • 22
  • 62
user2346571
  • 1,275
  • 1
  • 8
  • 2
  • 3
    Here's a full example of all nine possibilities of alignments (top-middle-bottom and left-center-right): https://jsfiddle.net/webMac/0swk9hk5 – webMac May 03 '18 at 09:34
  • In 2020 we can use flexbox caniuse.com/#feat=flexbox – tonygatta Jan 31 '20 at 11:11
80
 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }
johannchopin
  • 7,327
  • 6
  • 22
  • 62
  • 9
    I think this solution is the quickest and easiest to understand. Perhaps it's because I wasn't patient enough to grok the selected answer. Flexbox all the things! – modulitos Aug 14 '18 at 06:30
  • 1
    The addition of `justify-content: center` fixed my lack of horizontal centering – Samuel Slade Dec 11 '19 at 13:01
  • Perfect solution. This should be on top. – m4heshd Feb 16 '21 at 14:19
  • Why do we need a combination of 2 styles to make vertical alignment working in all screen size? If I use only display:flex and resize my screen, the vertical alignment is lost however if both display and align-items are used it works. – Marc Roussel Mar 01 '21 at 02:30
53

It worked for me:

.vcontainer {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle;
}
johannchopin
  • 7,327
  • 6
  • 22
  • 62
Romain
  • 1,065
  • 10
  • 8
25

A technique from a friend of mine:

HTML:

<div style="height:100px; border:1px solid;">
    <p style="border:1px dotted;">I'm vertically centered.</p>
</div>

CSS:

div:before {content:" "; display:inline-block; height:100%; vertical-align:middle;}
div p {display:inline-block;}

DEMO here

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
abernier
  • 22,855
  • 18
  • 73
  • 103
  • 1
    this technique is described in more detail here: http://css-tricks.com/centering-in-the-unknown/ – nerdess Jul 08 '13 at 13:45
23

Vertically and horizontally align element

Use either of these. The result would be the same:

  1. Bootstrap 4
  2. CSS3

Enter image description here

1. Bootstrap 4.3+

For vertical alignment: d-flex align-items-center

For horizontal alignment: d-flex justify-content-center

For vertical and horizontal alignment: d-flex align-items-center justify-content-center

.container {
    height: 180px;
    width:100%;
    background-color: blueviolet;
}

.container > div {
  background-color: white;
  padding: 1rem;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
rel="stylesheet"/>

<div class="d-flex align-items-center justify-content-center container">
  <div>I am in Center</div>
</div>

2. CSS 3

.container {
    height: 180px;
    width:100%;
    background-color: blueviolet;
}

.container > div {
  background-color: white;
  padding: 1rem;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="container center">
    <div>I am in Center</div>
</div>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
WasiF
  • 15,431
  • 9
  • 81
  • 100
  • 1
    Both ways are basically the same since Bootstrap uses the same flex attributes in it's classes. – Mx. Jul 25 '19 at 08:37
  • Bootstrap isn't magic. It's subject to the very same CSS limitations affecting everyone. It's just hiding what it does from the avg. user. – JasonGenX Jan 24 '20 at 21:29
20

To position block elements to the center (works in Internet Explorer 9 and above), it needs a wrapper div:

.vcontainer {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
VuesomeDev
  • 3,876
  • 2
  • 30
  • 43
  • 2
    This method can cause elements to be blurry due to the element being placed on a “half pixel”. A solution for this is to set the perspective of the element. transform: perspective(1px) translateY(-50%); – Simon Oct 07 '17 at 02:04
16

Almost all methods needs to specify the height, but often we don't have any heights.

So here is a CSS 3 three-line trick that doesn't require to know the height.

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

It's supported even in IE9.

with its vendor prefixes:

.element {
    position: relative;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

Source: Vertical align anything with just 3 lines of CSS

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Shadoweb
  • 4,323
  • 1
  • 32
  • 44
  • but this seems work only when the height of element's parent is fixed. the property 'top' with percentage value only works in the container with fixed height, correct? – ucdream May 14 '14 at 06:05
  • Yes it works only for some cases, I had problems later with this methods... The thing is to have the most possibilities as possible and as soon as you need one you test all of them until you get the good one, because all methods got things that won't works in a specific case... – Shadoweb May 14 '14 at 08:46
16

All of them need to be vertically aligned within the div

Aligned how? Tops of the images aligned with the top of the text?

One of the images needs to be absolute positioned within the div.

Absolutely positioned relative to the DIV? Perhaps you could sketch out what you're looking for...?

fd has described the steps for absolute positioning, as well as adjusting the display of the H1 element such that images will appear inline with it. To that, i'll add that you can align the images by use of the vertical-align style:

#header h1 { display: inline; }
#header img { vertical-align: middle; }

...this would put the header and images together, with top edges aligned. Other alignment options exist; see the documentation. You might also find it beneficial to drop the DIV and move the images inside the H1 element - this provides semantic value to the container, and removes the need to adjust the display of the H1:

<h1 id=header">
   <img src=".." ></img>
   testing...
   <img src="..."></img>
</h1>
Community
  • 1
  • 1
Shog9
  • 146,212
  • 34
  • 221
  • 231
16

Use this formula, and it will work always without cracks:

#outer {height: 400px; overflow: hidden; position: relative;}
#outer[id] {display: table; position: static;}

#middle {position: absolute; top: 50%;} /* For explorer only*/
#middle[id] {display: table-cell; vertical-align: middle; width: 100%;}

#inner {position: relative; top: -50%} /* For explorer only */
/* Optional: #inner[id] {position: static;} */
<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>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Anita Mandal
  • 326
  • 3
  • 10
  • 2
    I've never seen in css this kind of selector "#outer[id]". What should that do? What if I will have class instead of id? – Alexa Adrian Feb 13 '17 at 12:17
11

My trick is to put a table inside the div with one row and one column, set 100% of width and height, and the property vertical-align:middle:

<div>

    <table style="width:100%; height:100%;">
        <tr>
            <td style="vertical-align:middle;">
                BUTTON TEXT
            </td>
        </tr>
    </table>

</div>

Fiddle: http://jsfiddle.net/joan16v/sbqjnn9q/

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
joan16v
  • 4,551
  • 2
  • 44
  • 45
  • 7
    This seems the best way to avoid a lot of head-scratching. I'm still confused as to why CSS doesn't have a vertical align standard. – Kokodoko Dec 11 '14 at 12:56
5

Three ways to make a center child div in a parent div

  • Absolute positioning method
  • Flexbox method
  • Transform/translate method

Enter image description here

Demo

/* First way */
.parent1 {
  background: darkcyan;
   width: 200px;
   height: 200px;
   position: relative;
}
.child1 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -15px;
}

/* Second way */
.parent2 {
  display: flex;
  justify-content: center;
  align-items: center;
  background: darkcyan;
  height: 200px;
  width: 200px;
}
.child2 {
  background: white;
  height: 30px;
  width: 30px;
}

/* Third way */
.parent3 {
  position: relative;
  height: 200px;
  width: 200px;
  background: darkcyan;
}
.child3 {
  background: white;
  height: 30px;
  width: 30px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="parent1">
  <div class="child1"></div>
</div>
<hr />

<div class="parent2">
  <div class="child2"></div>
</div>
<hr />

<div class="parent3">
  <div class="child3"></div>
</div>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
akhtarvahid
  • 6,733
  • 2
  • 14
  • 21
4

Using CSS to vertical center, you can let the outer containers act like a table, and the content as a table cell. In this format your objects will stay centered. :)

I nested multiple objects in JSFiddle for an example, but the core idea is like this:

HTML

<div class="circle">
  <div class="content">
    Some text
  </div>
</div>

CSS

.circle {
  /* Act as a table so we can center vertically its child */
  display: table;
  /* Set dimensions */
  height: 200px;
  width: 200px;
  /* Horizontal center text */
  text-align: center;
  /* Create a red circle */
  border-radius: 100%;
  background: red;
}

.content {
  /* Act as a table cell */
  display: table-cell;
  /* And now we can vertically center! */
  vertical-align: middle;
  /* Some basic markup */
  font-size: 30px;
  font-weight: bold;
  color: white;
}

The multiple objects example:

HTML

<div class="container">
  <div class="content">

    <div class="centerhoriz">

      <div class="circle">
        <div class="content">
          Some text
        </div><!-- content -->
      </div><!-- circle -->

      <div class="square">
        <div class="content">
          <div id="smallcircle"></div>
        </div><!-- content -->
      </div><!-- square -->

    </div><!-- center-horiz -->

  </div><!-- content -->
</div><!-- container -->

CSS

.container {
  display: table;
  height: 500px;
  width: 300px;
  text-align: center;
  background: lightblue;
}

.centerhoriz {
  display: inline-block;
}

.circle {
  display: table;
  height: 200px;
  width: 200px;
  text-align: center;
  background: red;
  border-radius: 100%;
  margin: 10px;
}

.square {
  display: table;
  height: 200px;
  width: 200px;
  text-align: center;
  background: blue;
  margin: 10px;
}

.content {
  display: table-cell;
  vertical-align: middle;
  font-size: 30px;
  font-weight: bold;
  color: white;
}

#smallcircle {
  display: inline-block;
  height: 50px;
  width: 50px;
  background: green;
  border-radius: 100%;
}

Result

Result

https://jsfiddle.net/martjemeyer/ybs032uc/1/

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Henk-Martijn
  • 1,894
  • 18
  • 24
4

I have found a new workaround to vertically align multiple text-lines in a div using CSS 3 (and I am also using bootstrap v3 grid system to beautify the UI), which is as below:

.immediate-parent-of-text-containing-div {
    height: 50px;         /* Or any fixed height that suits you. */
}

.text-containing-div {
    display: inline-grid;
    align-items: center;
    text-align: center;
    height: 100%;
}

As per my understanding, the immediate parent of text containing element must have some height.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Shivam
  • 1,996
  • 1
  • 16
  • 17
3

We may use a CSS function calculation to calculate the size of the element and then position the child element accordingly.

Example HTML:

<div class="box">
    <span><a href="#">Some Text</a></span>
</div>

And CSS:

.box {
    display: block;
    background: #60D3E8;
    position: relative;
    width: 300px;
    height: 200px;
    text-align: center;
}

.box span {
    font: bold 20px/20px 'source code pro', sans-serif;
    position: absolute;
    left: 0;
    right: 0;
    top: calc(50% - 10px);
}

a {
    color: white;
    text-decoration: none;
}

Demo created here: https://jsfiddle.net/xnjq1t22/

This solution works well with responsive div height and width as well.

Note: The calc function is not tested for compatiblity with old browsers.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dashrath
  • 2,021
  • 1
  • 25
  • 33
3

By default h1 is a block element and will render on the line after the first img, and will cause the second img to appear on the line following the block.

To stop this from occurring you can set the h1 to have inline flow behaviour:

#header > h1 { display: inline; }

As for absolutely positioning the img inside the div, you need to set the containing div to have a "known size" before this will work properly. In my experience, you also need to change the position attribute away from the default - position: relative works for me:

#header { position: relative; width: 20em; height: 20em; }
#img-for-abs-positioning { position: absolute; top: 0; left: 0; }

If you can get that to work, you might want to try progressively removing the height, width, position attributes from div.header to get the minimal required attributes to get the effect you want.

UPDATE:

Here is a complete example that works on Firefox 3:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
    <head>
        <title>Example of vertical positioning inside a div</title>
        <style type="text/css">
            #header > h1 { display: inline; }
            #header { border: solid 1px red; 
                      position: relative; }
            #img-for-abs-positioning { position: absolute;
                                       bottom: -1em; right: 2em; }
        </style>
    </head>

    <body>
        <div id="header">
            <img src="#" alt="Image 1" width="40" height="40" />
            <h1>Header</h1>
            <img src="#" alt="Image 2" width="40" height="40" 
                 id="img-for-abs-positioning" />
        </div>
    </body>
</html>
Mike Tunnicliffe
  • 10,204
  • 3
  • 28
  • 46
  • 4
    I should note that having the right DOCTYPE can sometimes make big differences to how CSS will render, especially on Internet Explorer. I'd recommend you chose a DOCTYPE known to align with a strict standards mode so you can expect more consistent behaviour between browsers. – Mike Tunnicliffe Sep 18 '08 at 17:14
  • 2
    I wouldn't 'expect' any consistency between browsers.. only way to be sure is to test :/ – Cocowalla Nov 10 '09 at 08:03
2

Using display flex, first you need to wrap the container of the item that you want to align:

<div class="outdiv">
    <div class="indiv">
        <span>test1</span>
        <span>test2</span>
    </div>
</div>

Then apply the following CSS content to wrap div or outdiv in my example:

.outdiv {
    display: flex;
    justify-content: center;
    align-items: center;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Dennis Don
  • 177
  • 2
  • 2
  • Code only answers are discouraged. Please add some explanation as to how this solves the problem, or how this differs from the existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/22410664) – Nick Mar 09 '19 at 02:02
2

My new favorite way to do it is with a CSS grid:

/* technique */

.wrapper {
  display: inline-grid;
  grid-auto-flow: column;
  align-items: center;
  justify-content: center;
}

/* visual emphasis */

.wrapper {
  border: 1px solid red;
  height: 180px;
  width: 400px;
}

img {
  width: 100px;
  height: 80px;
  background: #fafafa;
}

img:nth-child(2) {
  height: 120px;
}
<div class="wrapper">
  <img src="https://source.unsplash.com/random/100x80/?bear">
  <img src="https://source.unsplash.com/random/100x120/?lion">
  <img src="https://source.unsplash.com/random/100x80/?tiger">
</div>
Stephen
  • 7,809
  • 7
  • 38
  • 67
2

Using only a Bootstrap class:

  • div: class="container d-flex"
  • element inside div: class="m-auto"

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" crossorigin="anonymous">

<div class="container d-flex mt-5" style="height:110px; background-color: #333;">
  <h2 class="m-auto"><a href="https://hovermind.com/">H➲VER➾M⇡ND</a></h2>
</div>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Hassan Tareq
  • 800
  • 13
  • 32
1

Just use a one-cell table inside the div! Just set the cell and table height and with to 100% and you can use the vertical-align.

A one-cell table inside the div handles the vertical-align and is backward compatible back to the Stone Age!

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Joel Moses
  • 27
  • 1
0

I have been using the following solution (with no positioning and no line height) since over a year, it works with Internet Explorer 7 and Internet Explorer 8 as well.

<style>
.outer {
    font-size: 0;
    width: 400px;
    height: 400px;
    background: orange;
    text-align: center;
    display: inline-block;
}

.outer .emptyDiv {
    height: 100%;
    background: orange;
    visibility: collapse;
}

.outer .inner {
    padding: 10px;
    background: red;
    font: bold 12px Arial;
}

.verticalCenter {
    display: inline-block;
    *display: inline;
    zoom: 1;
    vertical-align: middle;
}
</style>

<div class="outer">
    <div class="emptyDiv verticalCenter"></div>
    <div class="inner verticalCenter">
        <p>Line 1</p>
        <p>Line 2</p>
    </div>
</div>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Arsh
  • 21
  • 1
0

This is my personal solution for an i element inside a div.

JSFiddle Example

HTML

<div class="circle">
    <i class="fa fa-plus icon">
</i></div>

CSS

.circle {
   border-radius: 50%;
   color: blue;
   background-color: red;
   height:100px;
   width:100px;
   text-align: center;
   line-height: 100px;
}

.icon {
  font-size: 50px;
  vertical-align: middle;
}
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
danigonlinea
  • 1,013
  • 1
  • 14
  • 17
0

For me, it worked this way:

<div style="width:70px; height:68px; float:right; display: table-cell; line-height: 68px">
    <a href="javascript:void(0)" style="margin-left: 4px; line-height: 2" class="btn btn-primary">Login</a>
</div>

The "a" element converted to a button, using Bootstrap classes, and it is now vertically centered inside an outer "div".

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
BernieSF
  • 1,318
  • 1
  • 23
  • 40
-3

Just this:

<div>
    <table style="width: 100%; height: 100%">
        <tr>
            <td style="width: 100%; height: 100%; vertical-align: middle;">
               What ever you want vertically-aligned
            </td>
        </tr>
    </table>
</div>

A one-cell table inside the div handles the vertical-align and is backward compatible back to the Stone Age!

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Joel Moses
  • 27
  • 1
-3
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
    <head>
        <style type="text/css">
            #style_center { position:relative; top:50%; left:50%; }
            #style_center_absolute { position:absolute; top:50px; left:50px; }
            <!--#style_center { position:relative; top:50%; left:50%; height:50px; margin-top:-25px; }-->
        </style>
    </head>

    <body>
        <div style="height:200px; width:200px; background:#00FF00">
            <div id="style_center">+</div>
        </div>
    </body>
</html>
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
pr0gg3r
  • 3,904
  • 1
  • 33
  • 25
-4

Here is just another (responsive) approach:

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

    .table {
        display: table;
        width:  auto;
        table-layout:auto;
        height: 100%;
    }
        .table:nth-child(even) {
            background: #a9edc3;
        }
        .table:nth-child(odd) {
            background: #eda9ce;
        }

    .tr {
        display: table-row;
    }
    .td {
        display: table-cell;
        width: 50%;
        vertical-align: middle;
    }

http://jsfiddle.net/herrfischerhamburg/JcVxz/

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
-8
<div id="header" style="display: table-cell; vertical-align:middle;">

...

or CSS

.someClass
{
   display: table-cell;
   vertical-align:middle;
}

Browser Coverage

Joe
  • 73,764
  • 18
  • 123
  • 142
dimarzionist
  • 17,679
  • 4
  • 19
  • 22
  • 2
    The vertical-align property does not apply since the div is display: block by default and nothing appears to have been done to change it. – Quentin Mar 12 '10 at 12:38
  • 3
    Apparently the display was updated to `table-cell`, which makes `vertical-align: middle;` work. Even better, it works without needing a nested wrapper/buffer div, and it works for both text and images (or both), *and* you don't need to change the position properties. – MSpreij Jun 24 '12 at 17:56
  • 3
    This one works. It changes the display to table-cell which takes the vertical-align property. No idea why people vote this down. – texasbruce Dec 17 '12 at 04:55
  • 1
    yes, as far as i know this is the least intrusive way to center anything verticaly in a div. +1 – Pma Jan 08 '13 at 00:22
  • Ok, maybe i was too quick with my conclusions... Adding display:table-cell breakes div margin and additionaly border is displayed outside div, border combined with border-radius displays rounded corners inside of the div istead of outside – Pma Jan 09 '13 at 09:42
  • on certain occasions there may one extra outer div required with style display:table – adax2000 Aug 11 '14 at 16:50
  • Is this answer completely wrong? – Peter Mortensen May 29 '21 at 13:34