By Abdu


2008-09-17 02:53:36 8 Comments

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>

26 comments

@Dennis Don 2019-03-08 15:43:52

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


.outdiv {
    display: flex;
    justify-content:center;
    align-items:center;
}

@Nick 2019-03-09 02:02:40

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

@WasiF 2018-01-30 13:49:18

There are two ways to align elements vertically and horizontally

1. Bootstrap 4.2.1

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

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

.container {
    height: 180px;
    width:100%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" 
rel="stylesheet"/>

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

2. CSS3

.container {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #17a2b8;
    height: 180px;
    width:100%;
}

.child {
  background-color: #f8f9fa;
  padding: 0.5rem;
}
<div class="container">
  <div class="child">I am in Center</div>
</div>

@Sameera Prasad Jayasinghe 2018-08-01 06:38:35

 .outer {
   display: flex;
   align-items: center; 
   justify-content: center;
 }

@modulitos 2018-08-14 06:30:09

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!

@Konrad Rudolph 2008-09-17 15:38:49

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.

@Emilie 2013-05-14 08:42:59

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.

@patricK 2013-08-24 20:00:44

I had this structure: <div height="##px"> 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

@Alex W 2013-10-16 19:14:19

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.

@Muhammad Umer 2014-05-22 17:28:04

list of hacks..ways...etc. jsfiddle.net/techsin/FAwku/1

@shaunhusain 2016-02-21 01:20:21

css-tricks.com/centering-css-complete-guide <-- some good options presented here, have found myself resorting to the table/table-cell solution most of the time though

@Meliodas 2017-04-26 12:28:31

Understanding vertical-align, or "How (Not) To Vertically Center Content 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.

@Konrad Rudolph 2017-04-26 15:07:20

@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.

@Meliodas 2017-04-27 20:34:09

@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?

@Gaurav Jain 2017-08-05 23:20:53

The options listed on the link don't work if your inner element is an image. jsfiddle.net/rhvqd52c

@Konrad Rudolph 2017-08-07 09:56:32

@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. <img> isn’t special in any way, it behaves like any other element here.

@benshabatnoam 2018-10-16 06:34:37

“How to center in CSS” is a great web tool indeed. 10x

@Shivam 2017-08-02 10:35:32

As per today, I have found a new workaround to vertically align multiple text-lines in a div using CSS3 (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, immediate parent of text containing element must have some height. I hope it will help you too. Thanks!

@Dashrath 2016-10-06 19:57:20

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.

@tronious 2016-02-10 01:56:33

I'm a .NET guy who just got into web programming. I didn't use CSS (well, a little bit). I used a little JavaScript to accomplish vertical centering along with jQuery's .css function.

I'm just posting everything from my test. It's probably not overly elegant, but it works so far.

script.

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

        <script type="application/javascript">
            function centerElementVertically(id) {
                var btnDivHeight = $(id).outerHeight();
                var prnt = $(id).parent();
                var parentHeight = prnt.outerHeight();

                var newTop = ((parentHeight - btnDivHeight) / 2) + 'px';
                var newPct = newTop / parentHeight+'%;';

                $(id).css({top: newTop});
            }

            function showAlert(){
                alert("alert");
            }

            $(window).load(()=>{
                centerElementVertically('#buttonRight');
                centerElementVertically('#buttonLeft');
                centerElementVertically('#testerbtn')
            });

            $(window).resize(()=>{
                centerElementVertically('#buttonRight');
                centerElementVertically('#buttonLeft');
                centerElementVertically('#testerbtn')
            })
        </script>

        <style>
            #div1 {
                position:relative;
                height: 33%;
                background-color: red;
                overflow: hidden;
            }
            #buttonLeft {
                position: relative;
                float:left;
                width:50%;
                height:20%;
                background-color: cornsilk;
            }
            #buttonRight {
                position: relative;
                float:right;
                width:50%;
                height:50%;
                background-color: darkorchid;
            }
            #testerbtn {
                position: absolute;
            }
            body {
                background-color: aqua;
            }
        </style>

        <body>
            <div id="div1">
                <div id="buttonLeft">
                    <button id="testerbtn">tester</button>
                </div>
                <div id="buttonRight"></div>
            </div>
        </body>
    </head>
</html>

@OverCoder 2016-06-07 13:17:07

You're teaching new web developers how to do things wrong, HTML is for defining content, CSS is for styling the HTML, and JavaScript is for manipulating both at runtime depending on conditions. Mixing up those can quickly lead to spaghetti and performance intensive code

@BernieSF 2015-07-07 21:13:38

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".

@pr0gg3r 2014-01-04 11:41:46

<!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>

@user1688793 2013-11-22 16:28:28

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/

@Joel Moses 2013-10-02 07:17:38

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!

@Joel Moses 2013-10-02 07:03:37

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!

@abernier 2012-04-16 20:19:19

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

@nerdess 2013-07-08 13:45:08

this technique is described in more detail here: css-tricks.com/centering-in-the-unknown

@Mr_Green 2013-09-13 05:08:48

Works just for a single line..

@Anita Mandal 2012-04-01 18:58:07

Use this formula, and it will works 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>

@Alexa Adrian 2017-02-13 12:17:52

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?

@Romain 2011-05-11 10:24:00

It worked for me:

.vcontainer {
    min-height: 10em;
    display: table-cell;
    vertical-align: middle;
}

@Pacerier 2012-10-12 07:57:47

So it's no longer "block" element?

@Ortomala Lokni 2014-06-30 13:12:18

Then if you want to horizontal align with margin : 0 auto, it won't work because of the display: table-cell

@user2346571 2013-05-03 11:11:34

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.

@webMac 2018-05-03 09:34:00

Here's a full example of all nine possibilities of alignments (top-middle-bottom and left-center-right): jsfiddle.net/webMac/0swk9hk5

@E. Serrano 2015-06-26 16:56:47

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 Explorer 10, and old (< 4.4) 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;
}

@Boris Burkov 2015-11-04 05:18:36

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?

@Yazid Erman 2016-02-09 09:23:16

Doesn't this solution work on IE8?!

@shaunhusain 2016-02-21 01:16:05

@YazidErman this solution depends on flexbox so no, only IE 10 and above support or any other modern browser 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.

@Blacksonic 2014-10-14 09:07:45

To position block elements to the center (works in IE9 and above), needs a wrapper div:

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

@Simon 2017-10-07 02:04:37

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%);

@Henk-Martijn 2015-12-16 19:35:20

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/

@joan16v 2014-10-14 15:26:29

My trick is to put inside the div a table with 1 row and 1 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/

@Kokodoko 2014-12-11 12:56:51

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.

@danigonlinea 2014-09-16 11:39:46

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;
}

@Arsh 2014-07-27 20:00:50

I have been using the following solution (with no positioning and no line height) since over a year, it works with IE 7 and 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>

@Shadowbob 2014-01-18 10:13:26

Almost all methods needs to specify the height, but often we don't have any heights.
So here is a CSS3 3 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: http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/

@ucdream 2014-05-14 06:05:17

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?

@Shadowbob 2014-05-14 08:46:15

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...

@dimarzionist 2008-09-17 03:01:23

<div id="header" style="display: table-cell; vertical-align:middle;">

...

or CSS

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

Browser Coverage

@Quentin 2010-03-12 12:38:54

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.

@MSpreij 2012-06-24 17:56:58

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.

@texasbruce 2012-12-17 04:55:38

This one works. It changes the display to table-cell which takes the vertical-align property. No idea why people vote this down.

@Pma 2013-01-08 00:22:42

yes, as far as i know this is the least intrusive way to center anything verticaly in a div. +1

@Pma 2013-01-09 09:42:30

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

@0lukasz0 2013-06-09 21:47:06

this doesn't work on floated elements

@adax2000 2014-08-11 16:50:36

on certain occasions there may one extra outer div required with style display:table

@Mike Tunnicliffe 2008-09-17 03:08:18

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 2008-09-18 17:14:30

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.

@Cocowalla 2009-11-10 08:03:40

I wouldn't 'expect' any consistency between browsers.. only way to be sure is to test :/

@Shog9 2008-09-17 04:34:51

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>

Related Questions

Sponsored Content

34 Answered Questions

[SOLVED] How to vertically align an image inside a div?

16 Answered Questions

[SOLVED] How to disable resizable property of textarea?

  • 2011-03-08 16:15:40
  • user549757
  • 1176733 View
  • 2360 Score
  • 16 Answer
  • Tags:   html css

35 Answered Questions

[SOLVED] How to make div not larger than its contents?

  • 2009-01-16 16:03:07
  • George Snider
  • 1247926 View
  • 1843 Score
  • 35 Answer
  • Tags:   html css width

28 Answered Questions

[SOLVED] How do I vertically align text in a div?

96 Answered Questions

[SOLVED] How to horizontally center a <div>?

42 Answered Questions

[SOLVED] How to vertically center a div for all browsers?

38 Answered Questions

[SOLVED] How do I vertically center text with CSS?

40 Answered Questions

[SOLVED] How to disable text selection highlighting?

20 Answered Questions

[SOLVED] Vertically align text next to an image?

24 Answered Questions

[SOLVED] How to align content of a div to the bottom?

Sponsored Content