I want to center a div vertically with CSS. I don't want tables or Javascript, but only pure CSS. I found some solutions, but all of them are missing Internet Explorer 6 support.

<body>
    <div>Div to be aligned vertically</div>
</body>

How can I center a div vertically in all major browsers, including Internet Explorer 6?

3 upvote
  flag
18 upvote
  flag
@MarcoDemaio Don't people constantly frown upon tables for layouts on here? – Chud37
11 upvote
  flag
@Chud37: it depends what you have to do, tables for layout are generally not versatile and long to type in code, with css you can easily change a 2 cols layout into a 3/4/5 sols layout etc. But in this case is different, using dozens of css tips-and-tricks for such a simple task that could be accomplished with a perfect cross-browser table, it's like attempting to enter in your house through the window instead of using the door. – Marco Demaio
2 upvote
  flag
The BEST answer to this question can be found at //allinonescript.com/a/13075912/5651 – jessegavin
upvote
  flag
Just see this answer that vertically align a div in other div. Vertically Aligning Divs – Lalit Kumar
upvote
  flag
@Chud37 Don't cargo-cult against tables without understanding why people hate them. Most people who hate them would have a hard time explaining why. – Roman Starkov
upvote
  flag
In case people don't care about older browser support: davidwalsh.name/css-vertical-center – Karolis Šarapnickis
upvote
  flag
@MarcoDemaio : Because using tables with valign doesn't work? :) – user2284570
upvote
  flag

40 Answers 11

Actually you need two div's for vertical centering. The div containing the content must have a width and height.

#container {
  position: absolute;
  top: 50%;
  margin-top: -200px;
  /* half of #content height*/
  left: 0;
  width: 100%;
}

#content {
  width: 624px;
  margin-left: auto;
  margin-right: auto;
  height: 395px;
  border: 1px solid #000000;
}
<div id="container">
  <div id="content">
    <h1>Centered div</h1>
  </div>
</div>

Here is the result

upvote
  flag
Thanks!!! Worked for me. Do you mind explain a little how you came up with it? – Dao Lam
3 upvote
  flag
it's an old trick... top 50% and the top margin negative half the height for the inner div – Manatax
25 upvote
  flag
it's assuming you have a fixed height for div. don't work when div can change height. – Andre Figueiredo
7 upvote
  flag
i have compiled a list of all ways that are useful..jsfiddle.net/k6ShD/4 – Muhammad Umer

Unfortunately — but not surprisingly — the solution is more complicated than one would wish it to be. Also unfortunately, you'll need to use additional divs around the div you want vertically centered.

For standards-compliant browsers like Mozilla, Opera, Safari, etc. you need to set the outer div to be displayed as a table and the inner div to be displayed as a table-cell — which can then be vertically centered. For Internet Explorer, you need to position the inner div absolutely within the outer div and then specify the top as 50%. The following pages explain this technique well and provide some code samples too:

There is also a technique to do the vertical centering using Javascript. Vertical alignment of content with JavaScript & CSS demonstrates it.

up vote 1024 down vote accepted

Below is the best all-around solution I could build to vertically & horizontally center a fixed-width, flexible height content box. Tested and working for recent versions of FF, Opera, Chrome, & Safari.

HTML

<div class="outer">
  <div class="middle">
    <div class="inner">

      <h1>The Content</h1>

      <p>Once upon a midnight dreary...</p>

    </div>
  </div>
</div>

CSS

.outer {
    display: table;
    position: absolute;
    height: 100%;
    width: 100%;
}

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

.inner {
    margin-left: auto;
    margin-right: auto; 
    width: 400px; /*whatever width you want*/
}

View A Working Example With Dynamic Content

I built in some dynamic content to test the flexibility. Would love to know if anyone sees any problems with it. Should work well for centered overlays also -- lightbox, pop-up, etc.

4 upvote
  flag
Worked perfectly when the inner div was a flexible height. I tested it in Chrome and IE7 without the outer div positioned absolutely and that worked as well. – Sabrina Leggett
upvote
  flag
Without an "absolute" outer DIV, any content on the page before it will push the whole block down. This makes it more independent of other page content. – Billbad
38 upvote
  flag
This seems to be the only solution that doesn't require any hard-coded heights. – Martijn
1 upvote
  flag
IE7 + display: inline-block? IE 5.5-7.0: natural inline elements only – biziclop
upvote
  flag
@biziclop Acknowledged. Let me figure out what I did there. – Billbad
2 upvote
  flag
width: /*whatever width you want*/;, everything but horizontal centering. : s – Bentley4
upvote
  flag
Can you update your answer with the very important HTML structure as well please? – MEM
2 upvote
  flag
1 upvote
  flag
upvote
  flag
you don't even need a width. i found a way to have dynamic height and width. Do it like on the page in the link, but set inner container to display table – Mephiztopheles
1 upvote
  flag
.outer {position:absolute;width:100%;height:100%} is not necessary, they are here simply for demonstrating. All we need is display:table, if anyone is confused as I was. – gfaceless
upvote
  flag
I'm trying to achieve this with a sticky header and footer unsuccessfully. Here's my trial, can you help me? – Shimmy
upvote
  flag
@Martijn : My solution not only doesn't require hardcoded heights, but it even doesn't require hardcoded widths! -> //allinonescript.com/questions/396145/… – John Slegers
2 upvote
  flag
Who would have thought almost in 2017 that tables are the best solution for centering an element with an unknown size. And you don't need to worry about the infamous blurred borders bug in Chrome. Thank you! – Saul Fautley
1 upvote
  flag
Great. I would like to add, for avoiding scrolling bars, reduce from 100% to 99% .outer class:.outer { display: table; position: absolute; height: 99%; width: 99%; } as this example link – Rafa
upvote
  flag
Awesome! I used this solution to create a very simple modal popup window with jQuery. – Santiago Trejo
2 upvote
  flag
Thank you @Billbad. Sorry to ruin the party but it doesn't work in flipping Opera Mini. I've been looking for a solution high and low for Opera Mini ( //allinonescript.com/questions/44448632/… ) . Screenshot of yours: oi64.tinypic.com/atklrd.jpg – ChristinaD
upvote
  flag
I've noticed that this needs 99% to avoid scroll bars. More important, this works with only the first two divs, say keep .outer and middle and plainly ignore the .innerand its style. I don't know what is the point of margin-left, margin-right set to auto since that doesn't center the element horizontally??!!! – user10089632
upvote
  flag
Perfect solution (y) – Ali

This is always where I go when I have to come back to this issue

For those who don't want to make the jump:

  1. Specify the parent container as position:relative or position:absolute.
  2. Specify a fixed height on the child container.
  3. Set position:absolute and top:50% on the child container to move the top down to the middle of the parent.
  4. Set margin-top:-yy where yy is half the height of the child container to offset the item up.

An example of this in code:

<style type="text/css">
    #myoutercontainer { position:relative }
    #myinnercontainer { position:absolute; top:50%; height:10em; margin-top:-5em }
</style>
...
<div id="myoutercontainer">
    <div id="myinnercontainer">
        <p>Hey look! I'm vertically centered!</p>
        <p>How sweet is this?!</p>
    </div>
</div>

I did it with this (change width, height, margin-top and margin-left accordingly):

.wrapper {
    width:960px;
    height:590px;
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-295px;
    margin-left:-480px;
}

<div class="wrapper"> -- Content -- </div>
upvote
  flag
Thats only good if you know the width/height of the DIV your trying to center. This isn't what the question is asking – egr103

I find this one most useful.. it gives the most accurate 'H' layout and is very simple to understand.

The benefit in this markup is that you define your content size in a single place -> "PageContent".
The Colors of the page background and its horizontal margins are defined in their corresponding divs.

<div id="PageLayoutConfiguration" 
     style="display: table;
     position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
     width: 100%; height: 100%;">

        <div id="PageBackground" 
             style="display: table-cell; vertical-align: middle;
             background-color: purple;">

            <div id="PageHorizontalMargins"
                 style="width: 100%;
                 background-color: seashell;">

                <div id="PageContent" 
                     style="width: 1200px; height: 620px; margin: 0 auto;
                     background-color: grey;">

                     my content goes here...

                </div>
            </div>
        </div>
    </div>

And here with CSS separated:

<div id="PageLayoutConfiguration">
     <div id="PageBackground">
          <div id="PageHorizontalMargins">
               <div id="PageContent">
                     my content goes here...
               </div>
          </div>
     </div>
</div>

#PageLayoutConfiguration{
   display: table; width: 100%; height: 100%;
   position:absolute; top: 0px; right: 0px; bottom: 0px; left: 0px;
}

#PageBackground{
   display: table-cell; vertical-align: middle;
   background-color: purple;
}

#PageHorizontalMargins{
   style="width: 100%;
   background-color: seashell;
}
#PageContent{
   width: 1200px; height: 620px; margin: 0 auto;
   background-color: grey;
}

One more I can't see on the list:

.Center-Container {
  position: relative;
  height: 100%;
}

.Absolute-Center {
  width: 50%;
  height: 50%;
  overflow: auto;
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
  border: solid black;
}
  • Cross-browser (including IE8-10 without hacks!)
  • Responsive with percentages and min-/max-
  • Centered regardless of padding (without box-sizing!)
  • height must be declared (see Variable Height)
  • Recommended setting overflow: auto to prevent content spillover (see Overflow)

Source: Absolute Horizontal And Vertical Centering In CSS

6 upvote
  flag
This worked for me, but I needed to have a fixed width and height in chrome for some reason – Ryan Knell
upvote
  flag
Thank you. I needed a fix where I didn't need to calculate px height or width and this worked perfectly. – GFoley83
6 upvote
  flag
Great solution, especially because you don't need a parent div – Luca Steeb
1 upvote
  flag
This does a stretch if the height is not fixed, other than that: nice solution – Bart Burg
upvote
  flag
If you have a width and height that are not 100%, use margin: auto; – Charles L.
upvote
  flag
Why does this fail when any of the parameters for position are not 0. For example if top is 30%. – Loren Shqipognja
upvote
  flag
Strange, I tried this with a progress bar and it put it at the top of the page above my menu. – rtaft
upvote
  flag
@rtaft, if the update work check it out otherwise check the provided link for full css. – user10089632
upvote
  flag
@LucaSteeb, unless you set the position=relative for the body element, then yes you need a parent to set that to it. – user10089632

to center the Div in a page check the fiddle link

#vh {
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}
.box{
    border-radius: 15px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);
    padding: 25px;
    width: 100px;
    height: 100px;
    background: white;
}
<div id="vh" class="box">Div to be aligned vertically</div>

Update 1 Another option is to use flex box check the fiddle link

.vh {
    background-color: #ddd;
    height: 400px;
    align-items: center;
    display: flex;
}
.vh > div {
    width: 100%;
    text-align: center;
    vertical-align: middle;
}
<div class="vh">
    <div>Div to be aligned vertically</div>
</div>

Update 2 Another option is to use CSS3 transform

#vh {
    position: absolute;
    top: 50%;
    left: 50%;
    /*transform: translateX(-50%) translateY(-50%);*/
    transform: translate(-50%, -50%);
}
.box{
    border-radius: 15px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);
    padding: 25px;
    width: 100px;
    height: 100px;
    background: white;
}
<div id="vh" class="box">Div to be aligned vertically</div>

3 upvote
  flag
Only works with fixed heights... – Armel Larcier
2 upvote
  flag
@ArmelLarcier, no, it works with relative height also. – user
1 upvote
  flag
50% height is fixed. It is not relative to content, but parent. – Armel Larcier
1 upvote
  flag
@ArmelLarcier That's incorrect. Relative units are percentages %, ems and rems. Absolute or fixed values are pixels or points. What you're referring to is "it only works with a declared height". Howevever, although this method described by Moes does require a height, when you declare it in relative units, percentage is the best, no matter how much content is inside the centered DIV that DIV will expand vertically to fit its content. That's the beauty of this method. The other good thing is that this method works in IE8/9/10 in case someone still needs to support those browsers. – Ricardo Zea
upvote
  flag
@ricardozea I don't mean to play stubborn but saying the centered div will expand vertically while remaining vertically centered is wrong. Try it. I know when I say the height must be "fixed", that it's not the right word. It is indeed relative, to its parent. Anyway I think Chris Coyer's method makes more sense, see my answer //allinonescript.com/a/21919578/1491212 It's compatible with IE8 AND does work on an element with no specified dimensions. – Armel Larcier
1 upvote
  flag
@ArmelLarcier It's all good. Is not wrong brother. Try it: codepen.io/shshaw/pen/gEiDt - Add paragraphs to the green box ;]. Granted, it uses Modernizr to accomplish the effect, but all in all it's doable. I saw your answer and the CSS-Tricks.com post as well, but that method doesn't make me happy, it uses extra markup and the CSS is too verbose. I think the best solution is either using flexbox or the transform: translate(-50%, -50%); technique. For IE8 I'd just leave it top/center aligned and move on. – Ricardo Zea
1 upvote
  flag
@ricardozea Well the codepen you linked to uses the "display: table" method and extra markup so I'm not surprised. Anyways, +1 to your last sentence. – Armel Larcier

This is the simplest method I found and I use it all the time (jsFiddle demo here)

Thank Chris Coyier from CSS Tricks for this article.

.v-wrap{
    height: 100%;
    white-space: nowrap;
    text-align: center;
}
.v-wrap:before{
    content: "";
    display: inline-block;
    vertical-align: middle;
    width: 0;
    /* adjust for white space between pseudo element and next sibling */
    margin-right: -.25em;
    /* stretch line height */
    height: 100%; 
}
.v-box{
    display: inline-block;
    vertical-align: middle;
    white-space: normal;
}
<div class="v-wrap">
    <article class="v-box">
        <p>This is how I've been doing it for some time</p>
    </article>
</div>

Support starts with IE8.

1 upvote
  flag
If all other solutions fail - this one will anyway work. I love it. +1 for mentioning Chris Coyier and posting this here! – Daniel Ziegler

This question is old enough, so if someone cares IE10+ only, can use flexbox:

.parent {
    width: 500px;
    height: 500px;
    background: yellow;
    
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    
    -webkit-justify-content: center;
    -ms-flex-pack: center;
    justify-content: center;
    
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
}

.centered {
    width: 100px;
    height: 100px;
    background: blue;
}
<div class="parent">
    <div class="centered"></div>
</div>

Flexbox support: http://caniuse.com/flexbox

upvote
  flag
Android < 4.4 doesn't support align-items: center; ! – André Fiedler
upvote
  flag
Actually, it does support align-items: center; caniuse.com/#search=align-items – t.mikael.d
upvote
  flag
@t.mikael.d You might want to take a closer look at that table. For Android < 4.4, it states "Only supports the old flexbox specification and does not support wrapping." – Nathan Osman
2 upvote
  flag
IE9 does not support flexbox. Maybe you meant "if someone cares about IE10+ only"? – Chris Bier
upvote
  flag
@ChrisBier Sure. Fixed. Thx. – bravedick

The answer from Billbad only works with fixed width of the .inner div. This solution works for dynamic width by adding the attribute text-align: center to the .outer div.

.outer {
  position: absolute;
  display: table;
  width: 100%;
  height: 100%;
  text-align: center;
}
.middle {
  display: table-cell;
  vertical-align: middle;
}
.inner {
  text-align: center;
  display: inline-block;
  width: auto;
}
<div class="outer">
  <div class="middle">
    <div class="inner">
      Content
    </div>
  </div>
</div>

upvote
  flag
Interesting! I'm using an almost identical technique! -> //allinonescript.com/questions/396145/… – John Slegers

I use this. Works in IE8+

height:268px - for display:table acts like min-height

CSS:

* {
  padding: 0;
  margin: 0;
}
body {
  background: #cc9999;
}
p {
  background: #f0ad4e;
}
#all {
  margin: 200px auto;
}
.ff-valign-wrap {
  display: table;
  width: 100%;
  height: 268px;
  background: #ff00ff;
}
.ff-valign {
  display: table-cell;
  height: 100%;
  vertical-align: middle;
  text-align: center;
  background: #ffff00;
}

HTML:

<body>

  <div id="all">
    <div class="ff-valign-wrap">
      <div class="ff-valign">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet, animi autem doloribus earum expedita, ipsum laboriosam nostrum nulla officiis optio quam quis quod sunt tempora tenetur veritatis vero voluptatem voluptates?</p>
      </div>
    </div>
  </div>

</body>

A modern way to center an element vertically would be to use flexbox.

What you need is a parent to decide the height and a child to center.

The example below will center a div to the center within your browser. What's important (in my example) is to set height:100% to body and html and then min-height:100% to your container.

body, html {
  background:#f5f5f5;
  box-sizing:border-box;
  height:100%;
  margin:0;
}

#center_container {
  align-items:center;
  display:flex;
  min-height:100%;
}

#center {
  background:white;
  margin:0 auto;
  padding:10px;
  text-align:center;
  width:200px;
}
<div id='center_container'>
  <div id='center'>I am center.</div>
</div>

Especially for parent divs with relative (unknown) height, the Centering in the unknown solution works great for me. There are some really nice code examples in the article.

Tested in Chrome, FF, Opera, IE.

/* This parent can be any width and height */
.block {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}
<div style="width: 400px; height: 200px;">
   <div class="block" style="height: 90%; width: 100%">
  <div class="centered">
	 <h1>Some text</h1>
	 <p>Any other text..."</p>
  </div> 
   </div>
</div>

There are so many answers, but I just found another way which worked for me.

<div class="container">
  <div class="vertical">
     <h1>Welcome</h1>
     <h2>Aligned Vertically</h2>
     <a href="#">Click ME</a>
   </div>
</div>

css

.vertical{
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

More info

The simplest way would be the following 3 lines of CSS:

position: relative;
top: 50%;
transform: translateY(-50%);

Following is an example:

div.outer-div {
  height: 170px;
  width: 300px;
  background-color: lightgray;
}

div.middle-div {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}
<div class='outer-div'>
  <div class='middle-div'>
    Test text
  </div>
</div>

1 upvote
  flag
note: doesn't work correct if the height of the outer div is set with "min-height: 170px" – Bart Burg
upvote
  flag
Interferes with z-index – ripper234
1 upvote
  flag
Doesn't work if content has float. – kolobok

Vertical & Horizontal CENTER

HTML

<div id="dialog">Centered Dialog</div>

CSS

#dialog {
    position:fixed; top:50%; left:50%; z-index:99991;
    width:300px; height:60px;
    margin-top:-150px;  /* half of the width */
    margin-left:-30px; /* half of the height */}

Enjoy!

By using Transform property we can do vertically center div easily.

.main-div {
    background: none repeat scroll 0 0 #999;
    font-size: 18px;
    height: 450px;
    max-width: 850px;
    padding: 15px;
}

.vertical-center {
    background: none repeat scroll 0 0 #1fa67a;
    color: #ffffff;
    padding: 15px;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -o-transform: translateY(-50%);
}
<div class="main-div">
    <div class="vertical-center">
        <span>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span>
    </div>
</div>

see here for full article

to vertical-align a box in web page, including IE6 you may use

  1. conditionnal comments
  2. haslayout propertie
  3. display:table-value for others (and now flex )

Fiddle

/* IE8 and others*/
.main {
  width:500px;
  margin:auto;
  border:solid;
  }
html {
  height:100%;
  width:100%;
  display:table;
  }
body {
  display:table-cell;
  vertical-align:middle;
  }
<!-- [if lte IE 7]>
<style>/* should be in the <head> */
html, body , .ie {
height:100%;
text-align:center;
white-space:nowrap;
}
.ie , .main{
display:inline;/* used with zoom in case you take a block elemnt instead an inline element*/
zoom:1;
vertical-align:middle;
text-align:left;
white-space:normal;
}
</style>
<b class="ie"></b>
<!--[endif]-->
<div class="main">
  <p>Fill it up with your content </p>
  <p><a href="https://jsfiddle.net/h8z24s5v/embedded/result/">JsFiddle versie</a></p>
</div>

Actually, Ie7 would bring some trouble here being the only wich will strictly apply height:100% on html/body elements.


But, this is past and today and who still minds old IEs, table/table-cell is just fine, display:flex is promising and display:grid will show up some day.

upvote
  flag
downvote on the simpliest and oldiest way to do it without needs of size nor taking elements of the flow ? – G-Cyr

Just do it : add the class @ your div :

.modal {
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  height: 240px;
}

and read this article for explanation. Note : Height is necessary.

Here is a simple way, with almost no code:

CSS code:

.main{
    height:100%;
}

.center{
    top:50%;
    margin-top:50%;
}

Html code:

<div class="main">
    <div class="center">
        Hi, I am centered!
    </div>
</div>

Your text will be in the middle of the page!

After a lot of research I finally found the ultimate solution. It works even for floated elements. View Source

.element {
    position: relative;
    top: 50%;
    transform: translateY(-50%); /* or try 50% */
}
1 upvote
  flag
This does works really well, provided you remember that the container element must have an implicit or explicit height; jsfiddle.net/14kt53un A minor gotcha to those who are relatively new to CSS. – Martyn Shutt
4 upvote
  flag
Out of all the answers, this is the most simplest! I hope others see your answer too! Thank you! By the way, 50% worked for me (not -50%) – The Codesee

I know the answers is already given, but I think that link can be useful for the central alignment in all cases: howtocenterincss.com

best thing to do would be:

#vertalign{
  height:300px;
  width: 300px;
  position:absolute;
  top: calc(50vh - 150px); 
}

150px because that's half of the div's height in this case.

The three line code using transform works practically on modern browsers and IE

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

I am adding this answer since I found some incompleteness in the previous version of this answer (and stackoverflow won't allow me to simply comment).

  1. 'position' relative messes up the styling if the current div is in the body and has no container div. However 'fixed' seems to work but it obviously fixes the content in the center of the viewport position: relative

  2. Also I used this styling for centering some overlay divs and found that in Mozilla all elements inside this transformed div had lost their bottom borders. Possibly a rendering issue. But adding just the minimal padding to some of them rendered it correctly. Chrome and IE (surprisingly) rendered the boxes without any need for padding mozilla without inner paddings mozilla with paddings

Declare this Mixin:

@mixin vertical-align($position: relative) {
  position: $position;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Then include it in your element:

.element{
    @include vertical-align();
}
upvote
  flag
this is plain css? what about browser support? – Arnold Roa

This one working in my case. Tested in firefox.

#element {
    display: block;
    transform: translateY(50%);
    -moz-transform: translateY(50%);
    -webkit-transform: translateY(50%);
    -ms-transform: translateY(50%);
}

The div's height and parent's height are dynamic. I use it when there are other element on the same parent which is higher than the target element, where both are positioned horizontally inline.

Centering only vertically

If you don't care about IE6 and IE7, you can use a technique that involves two containers.

The outer container :

  • should have display: table;

The inner container :

  • should have display: table-cell;
  • should have vertical-align: middle;

The content box :

  • should have display: inline-block;

You can add any content you want to the content box without caring about its width or height!

Demo :

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

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

.centered-content {
    display: inline-block;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
        Malcolm in the Middle
     </div>
   </div>
</div>

See also this Fiddle!


Centering horizontally and vertically

If you want to center both horizontally and vertically, you also need the following.

The inner container :

  • should have text-align: center;

The content box :

  • should re-adjust the horizontal text-alignment to eg. text-align: left; or text-align: right;, unless you want text to be centered

Demo :

body {
    margin : 0;
}

.outer-container {
    position : absolute;
    display: table;
    width: 100%; /* This could be ANY width */
    height: 100%; /* This could be ANY height */
    background: #ccc;
}

.inner-container {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

.centered-content {
    display: inline-block;
    text-align: left;
    background: #fff;
    padding : 20px;
    border : 1px solid #000;
}
<div class="outer-container">
   <div class="inner-container">
     <div class="centered-content">
         Malcolm in the Middle
     </div>
   </div>
</div>

See also this Fiddle!

1 upvote
  flag
This answer is similar to this one: //allinonescript.com/a/24570521/363573. – Stephan
upvote
  flag
You forgot to horizontally center the content. Add text-align:center; to the .inner-container. – Doug S
upvote
  flag
@DougS : I didn't forget to horizontally center the content. I did not add horizontal centering because the question only mentions vertical centering. – John Slegers
upvote
  flag
@DougS : I just added some info on how to also center horizontally! – John Slegers

Flexbox solution

Notes
1. The parent element is given the class name.
2. Add flex vendor prefixes if required by your supported browsers.

.verticallyCenter {
  display: flex;
  align-items: center;
}
<div class="verticallyCenter" style="height:200px; background:beige">
    <div>Element centered vertically</div>
</div>

upvote
  flag
Note justify-content: center will center items horizontally as well – Peter Berg

This is by far the easiest approach, works on non block elements as well, the only downside is, it's Flexbox, thus, older browsers will not support this.

<div class="sweet-overlay">
<img class="centered" src="http://jimpunk.com/Loading/loading83.gif" />
</div>

Link to codepen:

http://codepen.io/damianocel/pen/LNOdRp

The important point here is, for vertical centering, we need to define a parent element(container) and the img must have a smaller height than the parent element.

This method doesn't use any transform. so it doesn't have a problem with the output becoming blurry

position: absolute;
width: 100vw;
top: 25%;
bottom: 25%;
text-align: center;

This worked in my case (only tested in modern browsers):

.textthatneedstobecentered {
  margin: auto;
  top: 0; bottom: 0;
}

Just write this css and know more please go through : This articale- vertical-align-anything-with-just-3-lines-of-css

.element {
position: relative;
top: 50%;
transform: perspective(1px) translateY(-50%);
}
upvote
  flag
CSS transforms can cause distortions in text and borders (when the math results in fractional pixels). – Nathan K

Now flexbox solution is very easy way for modern browsers, so I recommend this for you

.container{
   display: flex;
    align-items: center;
    justify-content: center;
    height:100%;
  
  }

body, html{
  height:100%;
  }
<div class="container">
    <div>Div to be aligned vertically</div>
</div>

3 upvote
  flag
This should be much higher on the list – Peter Berg
upvote
  flag
worked for me without height:100%; thanks – Sameera R.
upvote
  flag
If you've got a navbar, you can tweak the height using height: calc(100% - 55px) or whatever the height of your navbar is. – Adrian
upvote
  flag
Very helpful, thanks. – slorenzo

The following link presents a simple way of doing it with just 3 lines in your CSS:

Vertical align anything with just 3 lines of CSS.

Credits to: Sebastian Ekström.

I know the question has already an answer however I saw utility in the link for its simplicity.

The contents can be easily centered by using flexbox. The following code shows the CSS for the container inside which the contents needs to be centered:

.absolute-center {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

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

    align-items: center;
}

This solution worked for me if you have a block element (e. g. ). I used the colors to make the solution clearer.

HTML:

<main class="skin_orange">
<p>As you can the the element/box is vertically centered</p>
<div class="bigBox skin_blue">Blue Box</div>
</main>

CSS:

main {
    position: relative;
    width: 400px;
    height: 400px;
}

.skin_orange {
    outline: thin dotted red;
    background: orange;
}

.bigBox {
    width: 150px;
    height: 150px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
}

.skin_blue {
    background-color: blue;
}

JSFiddle Code Demo

.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* (x, y)  => position */
  -ms-transform: translate(-50%, -50%); /* IE 9 */
  -webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */    
}

.vertical {
  position: absolute;
  top: 50%;
  //left: 0;
  transform: translate(0, -50%); /* (x, y) => position */
}

.horizontal {
  position: absolute;
  //top: 0;
  left: 50%;
  transform: translate(-50%, 0); /* (x, y)  => position */
}

div {
  padding: 1em;
  background-color: grey; 
  color: white;
}  
<body>
  <div class="vertical">Vertically left</div>
  <div class="horizontal">Horizontal top</div>
  <div class="center">Vertically Horizontal</div>  
</body>

Related: Center a Image

Not answering for browser compatibility but to also mention the new Grid and the not so new Flexbox feature.

Grid

From: Mozilla - Grid Documentation - Align Div Vertically

Browser Support: Grid Browser Support

CSS:

.wrapper {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 10px;
  grid-auto-rows: 200px;
  grid-template-areas: 
    ". a a ."
    ". a a .";
}
.item1 {
  grid-area: a;
  align-self: center;
  justify-self: center;
}

HTML:

<div class="wrapper">
 <div class="item1">Item 1</div>
</div>

Flexbox

Browser Support: Flexbox Browser Support

CSS:

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
align-items: center;
justify-content: center;

I think a solid solution for all browsers without using flexbox - "align-items: center;" is a combination of display: table and vertical-align: middle;.

css

.vertically-center
{
    display: table;

    width: 100%;  /* optional */
    height: 100%; /* optional */
}

.vertically-center > div
{
    display: table-cell;
    vertical-align: middle;
}

html

<div class="vertically-center">
    <div>
        <div style="border: 1px solid black;">some text</div>
    </div>
</div>

‣demo: https://jsfiddle.net/6m640rpp/

Not the answer you're looking for? Browse other questions tagged or ask your own question.