How can I horizontally center a <div> within another <div> using CSS (if it's even possible)?

<div id="outer">  
  <div id="inner">Foo foo</div>
</div>
upvote
  flag
Of those great answers, I just want to highlight that you must give "#inner" a "width", or it will be "100%", and you can't tell if it's already centered. – Jony

80 Answers 11

up vote 3806 down vote accepted

You can apply this CSS to the inner <div>:

#inner {
  width: 50%;
  margin: 0 auto;
}

Of course, you don't have to set the width to 50%. Any width less than the containing <div> will work. The margin: 0 auto is what does the actual centering.

If you are targeting IE8+, it might be better to have this instead:

#inner {
  display: table;
  margin: 0 auto;
}

It will make the inner element center horizontally and it works without setting a specific width.

Working example here:

#inner {
  display: table;
  margin: 0 auto;
}
<div id="outer" style="width:100%">
  <div id="inner">Foo foo</div>
</div>

8 upvote
  flag
For the vertical centering I usually use "line-height" (line-height == height). This is simple and nice but it's only working with a one line content text :) – Nicolas Guillaume
1 upvote
  flag
in some cases writing !important clause for margin style of inner div would be necessary, e.g. when you wrote something like this outer div {margin: 0.5em;} – pepkin88
upvote
  flag
what about IE6? Does anybody know how to make it work in that 'stupid' browser? – Bakhtiyor
upvote
  flag
ya this works fine in ie6, just tested it. – Basit
64 upvote
  flag
You have to use the !DOCTYPE tag on your html page to make it work well on IE. – Fabio
upvote
  flag
margin auto; works on chrome and firefox without 0px; – Pramod
upvote
  flag
upvote
  flag
can someone explain how display:table works? why do elements with this styling applied automatically shrink to the size of the inner elements – Zhanger
9 upvote
  flag
Note that it may be necessary to add "float:none;" for the #inner. – Mert Mertce
upvote
  flag
@Zhanger FYI: <div style="display: table;">stuff</div> is the same as <table>stuff</table>. Assigning the display that way just tells the browser to render the element as a table. – SpYk3HH
11 upvote
  flag
You also set the top and bottom margins to 0, which is unrelated. Better putting margin-left: auto; margin-right: auto I think. – Emmanuel Touzery
upvote
  flag
To support mobile browsers, I do not recommend using width: 50%. Use something like max-width: 300px instead. – rybo111
1 upvote
  flag
This works fine on Chrome but does NOT support mobile browsers like Safari. – Sam Su
upvote
  flag
@Justin Poliey Your solution worked but can you please explain your answer. – vaibhav jain
upvote
  flag
This works for me setting #inner's width to 100%. – charliebrownie
upvote
  flag
CSS margin:0 auto will not work when the div has position property other than relative, like in the case of position:absolute – sarath
upvote
  flag
Why do we need to specify the width ? – HelloWorldNoMore
9 upvote
  flag
Not necessarily margin:0 auto: it can be margin: <whatever_vertical_margin_you_need> auto second being the horizontal margin. – YakovL
upvote
  flag
Why is text-align: center; obsolete? – Winter
upvote
  flag
As usual with stupid css this does not work because some other element is making it display to the left. How do I explain to a non-programmer that I cannot position a box in the centre of the screen? – Paul McCarthy
upvote
  flag
This is far from being a perfect solution as anything inside the inner DIV must be displayed as a table's element – Billal BEGUERADJ
1 upvote
  flag
voted most but not a better solution. the best way to do this is to use the combination of div and span tag, block css property and cross browser inline-block, and text center will do the simple magin – amachree tamunoemi
upvote
  flag
Why this doesn't work if inner element is button and not a div. – Saurabh Tiwari
upvote
  flag
Because "input" is inline element and must be centered by "text-align: center". – Simon Logic
upvote
  flag
"The margin: 0 auto is what does the actual centering." - can someone explain the magic behind this? – Andrew Grimm

It cannot be centered if you don't give it a width, otherwise it will take, by default the whole horizontal space.

40 upvote
  flag
and if you don't know the width? Say because the content is dynamic? – gman

Set the width and set margin-left and margin-right to auto. That's for horizontal only, though. If you want both ways, you'd just do it both ways. Don't be afraid to experiment, it's not like you'll break anything

If you don't want to set a fixed width on the inner div you could do something like this:

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

#inner {
  display: inline-block;
}
<div id="outer">  
    <div id="inner">Foo foo</div>
</div>

That makes the inner div into an inline element that can be centered with text-align.

12 upvote
  flag
@SabaAhang the correct syntax for that would be float: none; and is probably only needed because #inner has inherited a float of either left or right from somewhere else in your CSS. – Doug McLean
5 upvote
  flag
This is a nice solution. Just keep in mind that inner will inherit text-align so you may want to set inner's text-align to initial or some other value. – pmoleri
upvote
  flag
This is actually the correct answer. – Joe DeRose

I recently had to center a "hidden" div (ie, display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery to display the hidden div & then update the CSS to the automatic generated width of the table and change the margin to center it. (The display toggle is triggered by clicking on a link, but this code wasn't neccessary to display.)

NOTE: I'm sharing this code because Google brought me to this Stack Overflow solution & everything would have worked except that hidden elements don't have any width & can't be resized/centered until after they are displayed.

$(function(){
  $('#inner').show().width($('#innerTable').width()).css('margin','0 auto');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="inner" style="display:none;">
  <form action="">
    <table id="innerTable">
      <tr><td>Name:</td><td><input type="text"></td></tr>
      <tr><td>Email:</td><td><input type="text"></td></tr>
      <tr><td>Email:</td><td><input type="submit"></td></tr>
    </table>
  </form>
</div>

Suppose that your div is 200px wide:

.centered {
  position: absolute;
  left: 50%;
  margin-left: -100px;
}

Make sure the parent element is positioned i.e. relative, fixed, absolute, or sticky.

If you don't know the width of your div, you can use transform:translateX(-50%); instead of the negative margin.

https://jsfiddle.net/gjvfxxdj/

upvote
  flag
This doesn't work in Safari – cesards
upvote
  flag
I don't like this solution because when the inner element is too broad for the screen, you can't scroll over the whole element horizontally. margin: 0 auto works better. – Aloso
upvote
  flag
why do u put margin left: -100, this will not work – Robert Limanto
upvote
  flag
I've read that it's the only method that will work in IE6/7 – Andy
upvote
  flag
margin-left: auto; margin-right: auto; centres a block level element – Michael Neal
upvote
  flag
The default width for most block level elements is auto, which fills the available area on screen. Just being centered places it in the same position as left alignment. If you wish it to be visually centered you should set a width (or a max-width although Internet Explorer 6 and earlier do not support this, and IE 7 only supports it in standards mode). – Michael Neal

CSS3's box-align property

#outer {
    width:100%;
    height:100%;
    display:box;
    box-orient:horizontal;
    box-pack:center;
    box-align:center;
}
6 upvote
  flag
Make sure you read this answer first before you go about implementing this solution. – cimmanon

If you don't want to set a fixed width and don't want the extra margin, add display: inline-block to your element.

You can use:

#element {
    display: table;
    margin: 0 auto;
}
3 upvote
  flag
same requirements as display:inline-block too (quirksmode.org/css/display.html) – montrealmike
upvote
  flag
I used this, too, but I've never encountered display: table; before. What does it do? – Matt Cremeens

For Firefox & Chrome:

<div style="width:100%;">
  <div style="width: 50%; margin: 0px auto;">Text</div>
</div>

For IE, Firefox & Chrome:

<div style="width:100%; text-align:center;">
  <div style="width: 50%; margin: 0px auto; text-align:left;">Text</div>
</div>

The text-align: property is optional for modern browsers, but necessary in IE Quirks Mode for legacy browsers support.

5 upvote
  flag
There is no need for text-align property. It's completely un-necessary. – Touhid Rahman
upvote
  flag
text-align is actually necessary for it to work in IE quicks mode, so if you don't mind adding a little expression to support older browsers keep it there. (IE8 with IE8 rules and IE7 rules both work without text-align, so may be it's only IE6 and older that are concerned) – heytools

Best approaches with CSS 3

box model:

#outer{
    width:100%;

    /* Firefox */
    display:-moz-box;
    -moz-box-pack:center;
    -moz-box-align:center;

    /* Safari and Chrome */
    display:-webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;

    /* W3C */
    display:box;
    box-pack:center;
    box-align:center;
}
#inner{
    width:50%;
}

According to your usability you may also use the box-orient, box-flex, box-direction properties.

flex :

#outer {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}

Read more about centering the child elements

And this explains why box model is best approach.

upvote
  flag
it also works for me when inner div have float: left; – Tareq
19 upvote
  flag
Make sure you read this answer first before you go about implementing this solution. – cimmanon
3 upvote
  flag
Safari, as of now, still requires -webkit flags for flexbox (display: -webkit-flex; and -webkit-align-items: center; and -webkit-justify-content: center;) – Joseph Hansen

Centering: Auto-width Margins

This box is horizontally centered by setting its right and left margin widths to "auto". This is the preferred way to accomplish horizontal centering with CSS, and works very well in most browsers with CSS2 support. Unfortunately, IE5/Win does not respond to this method - a shortcoming of that browser, not the technique.

There is a simple workaround. (A pause while you fight back the nausea induced by that word.) Ready? IE5/Win incorrectly applies the CSS "text-align" attribute to block-level elements. Declaring "text-align:center" for the containing block-level element (often the BODY element) horizontally centers the box in IE5/Win. There is a side effect of this workaround: the CSS "text-align" attribute is inherited, centering inline content. It is often necessary to explicitly set the "text-align" attribute for the centered box, counteracting the effects of the IE5/Win workaround. The relevant CSS follows.

body {
    margin:50px 0px; padding:0px;
    text-align:center;
    }

#Content {
    width:500px;
    margin:0px auto;
    text-align:left;
    padding:15px;
    border:1px dashed #333;
    background-color:#eee;
    }

http://bluerobot.com/web/css/center1.html

3 upvote
  flag
That's not centering the div, that's centering the text. – Duh-Wayne-101

The way I usually do it is using absolute position:

#inner{
    left: 0;
    right: 0;
    margin-left: auto;
    margin-right: auto;
    position: absolute;
}

The outer div doesn't need any extra propertites for this to work.

Some posters have mentioned the css3 way to center using display:box

This syntax is outdated and shouldn't be used anymore.[See also this post] So just for completeness here is the latest way to center in css3 using the Flexible Box Layout Module

So if you have simple markup like:

<div class="box">
  <div class="item1">A</div>
  <div class="item2">B</div>
  <div class="item3">C</div>
</div>

...and you want to center your items within the box, here's what you need on the parent element (.box):

.box {
    display: flex;
    flex-wrap: wrap; /* optional. only if you want the items to wrap */
    justify-content: center; /* for horizontal alignment */
    align-items: center; /* for vertical alignment */
}

.box {
  display: flex;
  flex-wrap: wrap;
  /* optional. only if you want the items to wrap */
  justify-content: center;
  /* for horizontal alignment */
  align-items: center;
  /* for vertical alignment */
}
* {
  margin: 0;
  padding: 0;
}
html,
body {
  height: 100%;
}
.box {
  height: 200px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  border: 2px solid tomato;
}
.box div {
  margin: 0 10px;
    width: 100px;
}
.item1 {
  height: 50px;
  background: pink;
}
.item2 {
  background: brown;
  height: 100px;
}
.item3 {
  height: 150px;
  background: orange;
}
<div class="box">
  <div class="item1">A</div>
  <div class="item2">B</div>
  <div class="item3">C</div>
</div>

If you need to support older browsers which use older syntax for flexbox here's a good place to look.

upvote
  flag
upvote
  flag
what do you mean by "syntax is outdated", is it deprecated? – Konga Raju
3 upvote
  flag
The Flexbox specification has gone through 3 major revisions. The most recent draft is from Sept 2012, which officially deprecates all previous drafts. However, browser support is spotty (particularly old Android browsers): //allinonescript.com/questions/15662578/… – cimmanon
upvote
  flag
This worked for me in Chrome when Justin Poliey's version didn't. – Vern Jensen
upvote
  flag
Isn't the "justify-content: center;" for the vertical alignment and the "align-items: center;" for the horizontal alignment? – Wouter Vanherck
2 upvote
  flag
@WouterVanherck it depends on the flex-direction value. If it is 'row' (the default) - then justify-content: center; is for the horizontal alignment (like I mentioned in the answer) If it is 'column' - then justify-content: center; is for the vertical alignment. – Danield

I realize I'm pretty late to the game, but this is a very popular question, and I recently found an approach I haven't seen mentioned anywhere here, so I figured I'd document it.

#outer {
    position: absolute;
    left: 50%;
}

#inner {
    position: relative;
    left: -50%;
}

EDIT: both elements must be the same width to function correctly.

upvote
  flag
Just set this rule for #inner only: #inner { position:relative; left:50%; transform:translateX(-50%); }. This works for any width. – Jose Rui Santos

I have applied inline style to inner div. Use this one.

<div id="outer" style="width:100%">  
    <div id="inner" style="display:table;margin:0 auto;">Foo foo</div>
</div>

This is my answer.

#outerDiv {
  width: 500px;
}

#innerDiv {
  width: 200px;
  margin: 0 auto;
}
<div id="outerDiv">
  <div id="innerDiv">Inner Content</div>
</div>

I've created this example to show how to vertically and horizontally align.

Code is basically this:

#outer {
  position: relative;
}

and...

#inner {
  margin: auto;  
  position: absolute;
  left:0;
  right: 0;
  top: 0;
  bottom: 0;
} 

and it will stay in the center even when you re-size your screen.

10 upvote
  flag
+1 for this method, I was about to answer with it. Note that you must declare a width on the element you wish to center horizontally (or height if centering vertically). Here's a comprehensive explanation: codepen.io/shshaw/full/gEiDt. One of the more versatile and widely-supported methods of centering elements vertically and/or horizontally. – stvnrynlds
5 upvote
  flag
You cannot use padding within the div, but if you want to give the illusion use a border of the same color. – Squirrl
upvote
  flag
I think for this method to work, you need to set the with and height of inner div – Nicolas S.Xu

How about the below CSS for #inner div:

#inner {
  width: 50%;
  margin-left: 25%;
}

I mostly use this CSS to center divs.

upvote
  flag
can also be margin-right: 25% – Rajesh

You can do something like this

#container {
   display: table;
   width: <width of your container>;
   height: <height of your container>;
}

#inner {
   width: <width of your center div>;
   display: table-cell;
   margin: 0 auto;
   text-align: center;
   vertical-align: middle;
}

This will also align the #inner vertically. If you don't want to, remove the display and vertical-align properties;

Chris Coyier who wrote an excellent post on 'Centering in the Unknown' on his blog. It's a roundup of multiple solutions. I posted one that isn't posted in this question. It has more browser support then the flexbox-solution, and you're not using display: table; which could break other things.

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

/* The ghost, nudged to maintain perfect centering */
.outer:before {
  content: '.';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  width:0;
  overflow:hidden;
}

/* The element to be centered, can
   also be of any width and height */ 
.inner {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

Nice thing I recently found, mixing the use of line-height+vertical-align and the 50% left trick, you can center a dynamically sized box inside another dynamically sized box, on both the horizontal and vertical using pure CSS.

Note you must use spans (and inline-block), tested in modern browsers + IE8. HTML:

  <h1>Center dynamic box using only css test</h1>
    <div class="container">
        <div class="center">
            <div class="center-container">
                <span class="dyn-box">
                    <div class="dyn-head">This is a head</div>
                    <div class="dyn-body">
                        This is a body<br />
                        Content<br />
                        Content<br />
                        Content<br />
                        Content<br />
                    </div>
                </span>
            </div>
        </div>
    </div>

CSS:

.container
{
    position:absolute;
    left:0;right:0;top:0;bottom:0;
    overflow:hidden;
}
.center
{
    position:absolute;
    left:50%; top:50%;
}
.center-container
{
    position:absolute;
    left:-2500px;top:-2500px;
    width:5000px;height:5000px;
    line-height:5000px;
    text-align:center;
    overflow: hidden;
}
.dyn-box
{
    display: inline-block;
    vertical-align: middle;
    line-height: 100%;

    /* Purely asthetic below this point */
    background: #808080;
    padding: 13px;
    border-radius: 11px;
    font-family: arial;
}
.dyn-head
{
    background:red;
    color:white;
    min-width: 300px;
    padding: 20px;
    font-size: 23px;
}
.dyn-body
{
    padding: 10px;
    background:white;
    color:red;
}

See example here.

Try playing around with

margin: 0 auto;

If you want to center your text too, try using:

text-align: center;
upvote
  flag
text-align work for text alignment in its container not for its container to its parent. – Lalit Kumar

one option is existed that i found every body say use

margin: auto 0;

but there is another option set this property for parent div , it is anytime work perfect

text-align:center;

and see , child go center

and finally css for you

#outer{
     text-align:center;
     display:block;/* or inline-block - base on your need*/
}

#inner
{
     position:relative;
     margin:0 auto; /* it is good to be */
}
upvote
  flag
text-align work for text alignment in its container not for its container to its parent. – Lalit Kumar
upvote
  flag
i test it , i problem with set child to center , must when you have more one child , more times margin:0 auto font answer , but , text-align center , for parent make this child be center , even if they are element and not be text , test and see what happen – Pnsadeghy
upvote
  flag
text-align center text only. You right at this time but when you write a container css which contains a child with different width and color your code does't work. Test it again!!!! – Lalit Kumar
upvote
  flag
See this example jsfiddle.net/uCdPK/2 and tell me what do you think about it!!!!! – Lalit Kumar
<center>

I am spoiled with the most simple center known?

</center>
upvote
  flag
This worked for me and am not sure why it isn't the answer. Can someone explain what is wrong with this? – DaveWalley
10 upvote
  flag
@DaveWalley though works there are 2 good reasons why this is not a good answer. 1st the question was for a CSS solution and this is a pure HTML solution. 2nd the CENTER tag was already deprecated in HTML 4 – Idra

For example see this link and the snippet below:

div#outer {
  height: 120px;
  background-color: red;
}

div#inner {
  width: 50%;
  height: 100%;
  background-color: green;
  margin: 0 auto;
  text-align:center; /* For Text alignment to center horizentaly. */
  line-height: 120px; /* For Text alignment to center verticaly. */
}
<div id="outer" style="width:100%;">  
  <div id="inner">Foo foo</div>
</div>

If you have a lot of children under a parent, so your css must be like this example on fiddle.

Html look likes this

<div id="outer" style="width:100%;">  
    <div class="inner"> Foo Text </div>
    <div class="inner"> Foo Text </div>
    <div class="inner"> Foo Text </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> </div>
    <div class="inner"> Foo Text </div>
</div>

Then see this example on fiddle.

If width of the content is unknown, you can use the following method that requires one extra element. Suppose we have these two elements:

  • outer (100% wide, suppose it is 1000px wide)
  • inner (no width defined, suppose it is 300px wide)

Proceed as follows:

  1. Wrap inner inside center-helper
  2. Float center-helper; it becomes same size as inner (this makes it 300px wide)
  3. Push center-helper 50% right relative to its parent (this places its left at 500px wrt. outer)
  4. Pull inner 50% left relative to its parent (this places its left at -150px wrt. center-helper which means its left is at 500 - 150 = 350px wrt. outer)
  5. Set overflow on outer to hidden

Here is the CSS:

.outer {
    overflow: hidden;
}
.center-helper {
    float: left;
    position: relative;
    left: 50%;
}
.inner {
    float: left;
    position: relative;
    left: -50%;
}

And here is the demo

Here is what you want in the shortest way.

JSFIDDLE

#outer {
    margin - top: 100 px;
    height: 500 px; /* you can set whatever you want */
    border: 1 px solid# ccc;
}

#inner {
    border: 1 px solid# f00;
    position: relative;
    top: 50 % ;
    transform: translateY(-50 % );
}
3 upvote
  flag
That centers it vertically. – Michael Terry

Well, I managed to find a solution that maybe will fit all situations, but uses javascript:

Here's the structure:

<div class="container">
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
  <div class="content">Your content goes here!</div>
</div>

And here's the javascript snippet:

$(document).ready(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

If you want to use it in a responsive approach, you can add the following:

$(window).resize(function() {
  $('.container .content').each( function() {
    container = $(this).closest('.container');
    content = $(this);

    containerHeight = container.height();
    contentHeight = content.height();

    margin = (containerHeight - contentHeight) / 2;
    content.css('margin-top', margin);
  })
});

I know I'm a bit late to answering this question, and I haven't bothered to read every single answer so this may be a duplicate. Here's my take:

inner { width: 50%; background-color: Khaki; margin: 0 auto; }
1 upvote
  flag
Yes, I believe this is a duplicate. The top answer by Justin Poliey has solved the problem in the same way. – Gui Imamura

Centering a div of unknown height and width

Horizontally and vertically. Works with reasonably modern browsers (FF, Safari/Webkit, Chrome, IE10, Opera, etc.)

.content {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>

Tinker with it further on Codepen or on JSBin

try this:

<div id="a">
    <div id="b"></div>
</div>

css:

#a{
   border:1px solid red;
   height:120px;
   width: 400px
}

#b{
   border:1px solid blue;
   height:90px;
   width: 300px;
   position:relative;
   margin-left:auto;  
   margin-right:auto;
}

The easiest way:

#outer {
  width:100%;
  text-align:center;
}
#inner {
  margin:auto;
  width:200px;
}
<div id="outer">
  <div id="inner">Blabla</div>
</div>

1 upvote
  flag
As your fiddle notes, #inner has to have a width set on it. – Michael Terry

i just use the simplest solution but it works in all browsers.

  <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>center a div within a div?</title>
<style type="text/css">
*{
    margin: 0;
    padding: 0;
}

#outer{
    width: 80%;
    height: 500px;
    background-color: #003;
    margin: 0 auto;
}

#outer p{
    color: #FFF;
    text-align: center;
}

#inner{
    background-color: #901;
    width: 50%;
    height: 100px;
    margin: 0 auto;

    }

    #inner p{
        color: #fff;
        text-align: center;
    }
</style>
</head>

<body>
<div id="outer"><p>this is the outer div</p>
    <div id="inner">
        <p>this is the inner div</p>
    </div>
</div>
</body>
</html>

i hope this helps!

If Anyone would like a Jquery for center align these divs

$(window).bind("load", function() {
    var wwidth = $("#outer").width();
    var width = $('#inner').width();
    $('#inner').attr("style", "padding-left: " + wwidth / 2 + "px; margin-left: -" + width / 2 + "px;");
});

First of all: You need to give a width to the second div: For example: HTML

<div id="outter">
 <div id="inner"Centered content">
</div
</div>

CSS:

 #inner{
  width:50%;
  margin:auto;
}

Note that if you don't give it a width it will take the whole width of the line

Instead of multiple wrappers and/or auto margins, this simple solution works for me:

<div style="top:50%; left:50%;
    height:100px; width:100px;
    margin-top:-50px; margin-left:-50px;
    background:url('lib/loading.gif') no-repeat center #fff;
    text-align:center;
    position:fixed; z-index:9002;">Loading...</div>

Puts the div at the center of the view (vertical and horizontal), sizes and adjusts for size, centers background image (vertical and horizontal), centers text (horizontal), and keeps div in the view and on top of the content. Simply place in html body and enjoy.

Another solution for this without having to set a width for one of the elements is using the CSS3 transform attribute.

#outer {
  position: relative;
}

#inner {
  position: absolute;
  left: 50%;

  transform: translateX(-50%);
}

The trick ist, that translateX(-50%) sets the #inner element 50 percent to the left of its own width. You can use the same trick for vertical alignment.

Here's a Fiddle showing horizontal and vertical alignment.

More information on Mozilla Developer Network.

2 upvote
  flag
One may need vendor prefixes as well : -webkit-transform: translate(-50%,0); -moz-transform: translate(-50%,0); -ms-transform: translate(-50%,0); -khtml-transform: translate(-50%,0); -o-transform: translate(-50%,0); – Skippy le Grand Gourou
#inner {
    width: 50%;
    margin: 0 auto;
}
upvote
  flag
Thnx for trying to help the OP :). You shouldn't add answers that are exactly the same as answers already provided. I'm guessing the collision is a mistake but this could have been completely copied and pasted from the accepted answer. – Rapnar

try out this

#outer{
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

#outer > #inner{
    display: inline-block;
    font-size: 19px;
    margin: 20px;
    max-width: 320px;
    min-height: 20px;
    min-width: 30px;
    padding: 14px;
    vertical-align: middle;
}
#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top:-20px; /* Half of your Height */
}

Depending on your circumstances, the simplest solution could be:

margin:0 auto; float:none;

Yes this is short and clean code for horizontal align. i hope you like this code.

.classname {
   display:box;
   margin:0 auto;width:500px /*-width set as per your requirement-*/;
}

I am sharing this answer for the designer who want to align their content horizontally and vertically both. Or You may say in the center of the web page. Please go to This Site to Download the File. Hope It will help.

Css Code

.ver-hor-div {
display: table-cell;
vertical-align: middle;
text-align:center;
}

the best way is using table-cell display (inner) that come exactly after a div with display tabel (outer) and set vertical align for inner div (with table-cell display) and every tag you use in the inner div placed in the center of div or page

note: you must set a specified height to outer

it is the best way you know without position relative or absolute and you can use it in every browser as same

#outer{
  display: table;
  height: 100vh;
  width: 100%;
}


#inner{ 
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
<div id="outer">  
    <div id="inner">
      <h1>
          set content center
      </h1>
      <div>
        hi this is the best way to align your items center
      </div>
    </div>
</div>

Centering only horizontally

In my experience, the best way to center a box horizontally, is to apply the following properties :

The container :

  • should have text-align : center;

The content box :

  • should have display: inline-block;

Demo :

.container {
  width: 100%;
  height: 120px;
  background: #ccc;
  text-align: center;
}

.centered-content {
  display: inline-block;
  background: #fff;
  padding: 20px;
  border: 1px solid #000;
}
<div class="container">
  <div class="centered-content">
    Center this!
  </div>
</div>

See also this Fiddle!


Centering both horizontally & vertically

In my experience, the best way to center a box both vertically and horizontally, is to use an additional container and apply the following properties :

The outher container :

  • should have display: table;

The inner container :

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

The content box :

  • should have display: inline-block;

Demo :

.outer-container {
  display: table;
  width: 100%;
  height: 120px;
  background: #ccc;
}

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

.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">
      Center this!
    </div>
  </div>
</div>

See also this Fiddle!

It is so simple.

Just decide what width you want to give to inner div and use the following css.

CSS

.inner{
  width:500px; //assumed width
  margin: 0 auto;
}

<div id="outer" style="width:100%;margin: 0 auto; text-align: center;">  
  <div id="inner">Foo foo</div>
</div>

After reading all the answers I did not see the one I prefer. This is how you can center an element in another.

jsfiddle - http://jsfiddle.net/josephtveter/w3sksu1w/

<p>Horz Center</p>
<div class="outterDiv">
    <div class="innerDiv horzCenter"></div>
</div>
<p>Vert Center</p>
<div class="outterDiv">
    <div class="innerDiv vertCenter"></div>
</div>
<p>True Center</p>
<div class="outterDiv">
    <div class="innerDiv trueCenter"></div>
</div>
.vertCenter
{
    position: absolute;
    top:50%;
    -ms-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
}

.horzCenter
{
    position: absolute;
    left: 50%;
    -ms-transform: translateX(-50%);
    -moz-transform: translateX(-50%);
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}

.trueCenter
{
    position: absolute;
    left: 50%;
    top: 50%;
    -ms-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

.outterDiv
{
    position: relative;
    background-color: blue;
    width: 10rem;
    height: 10rem;
    margin: 2rem;
}
.innerDiv
{
    background-color: red;
    width: 5rem;
    height: 5rem;
}

HTML:

<div id="outer">
  <div id="inner">
  </div>
</div>

CSS:

#outer{
  width:500px;
  background-color:#000;
  height:500px
}
#inner{
  background-color:#333;
  margin:0 auto;
  width:50%;
  height:250px;
}

Fiddle.

Add text-align:center; to parent div

#outer {
    text-align: center;
}

https://jsfiddle.net/7qwxx9rs/

or

#outer > div {
    margin: auto;
    width: 100px;
}

https://jsfiddle.net/f8su1fLz/

This method also works just fine:

div.container {
   display: flex;
   justify-content: center; /* for horizontal alignment */
   align-items: center;     /* for vertical alignment   */
}

For the inner <div>, the only condition is that its height and width must not be larger than the ones of its container.

You can attain this using the CSS Flexbox. You just need to apply 3 properties to the parent element to get everything working.

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

Have a look at the code below this will make you understand the properties much better.

Get to know more about CSS Flexbox

#outer {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  width: 100%;
  height: 200px;
 }
<div id="outer">  
  <div id="inner">Foo foo</div>
</div>

Give some width to inner div and add margin:0 auto; in CSS property.

.outer {
    text-align:center;
    width: 100%
}
upvote
  flag
only add text-align center in your perent div (outer) so their children class take that css autometicaly – amit bende

You can use the flexbox.

#inner {
   display: flex;
   justify-content: center;
}

You can learn more about it on this link: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

2 upvote
  flag
Please add some explanation what technologies you're using and how it's working. A reference link would be fine. – try-catch-finally

it's possible using CSS3 flexbox ,you have two methods when using flex box.

  1. set parent display:flex; and add properties {justify-content:center; ,align-items:center;} to your parent element.

#outer{
  display:flex;
  justify-content:center;
  align-items:center;
  }
<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>

  1. set parent display:flex and add margin:auto; to the child.

#outer{
  display:flex;
  }
#inner{
  margin:auto;
  }
<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>

Add css to your inner div. Set margin:0 auto and set it's width less than 100%, which is the width of the outer div.

   <div id="outer" style="width:100%"> 
        <div id="inner" style="margin:0 auto;width:50%">Foo foo</div> 
    </div>

This will give the desired result.

upvote
  flag
How is this different to the many other answers that seem to do the same? – Eiko

CSS

#inner {
  display: table;
  margin: 0 auto; 
}

HTML

<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>
<div id="outer" style="width:100%">  
  <div id="inner" style="text-align:center">Foo foo</div>
</div>

Easiest answer add margin:auto; to inner .

<div class="outer">
  <div class="inner">
    Foo foo
  </div>
</div>

css code

.outer{ width:100%; height:300px; background:yellow;}
.inner{width:30%; height:200px; margin:auto; background:red; text-align:center}

check my codepen link http://codepen.io/feizel/pen/QdJJrK

enter image description here

Just Simply Margin:0px auto

#inner{
 display:block;
 margin:0px auto;
 width:100px;
}
<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>

CSS3:

You can use the following style on the parent container to distribute child elements evenly horizontally:

display: flex;
justify-content: space-between;  // <-- space-between or space-around

A nice DEMO regarding the different values for justify-content.

enter image description here

CanIUse: Browser-Compatability

Try it!:

#containerdiv {
  display: flex;
  justify-content: space-between;
}

#containerdiv > div {  
  background-color:blue;
  width:50px;
  color:white;
  text-align:center;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="containerdiv">
    <div>88</div>
    <div>77</div>
    <div>55</div>
    <div>33</div>
    <div>40</div>
    <div>45</div>
  </div>
</body>
</html>

Flex have more than 97% browser support coverage, and might be the best way to solve these kind of problems within few lines:

#outer {
  display: flex;
  justify-content: center;
}

It can also be centered horizontally and vertically using absolute positioning, like this:

#outer{
    position: relative;
}

#inner{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%)
}

just use this in style

#inner{
left 40%
}
upvote
  flag
This doesn't explain why this should solve the problem or answer the question. – ItamarG3

Use below code.

HTML

<div id="outer">  
  <div id="inner">Foo foo</div>
</div>

CSS

#outer {
  text-align: center;
}
#inner{
  display: inline-block;
}

The best known way which is used widely and work in many browsers including the old ones, is using margin as below:

#parent {
  width: 100%;
  background-color: #cccccc;
}

#child {
  width: 30%; /*we need the width*/
  margin: 0 auto; /*this does the magic*/
  color: #ffffff;
  background-color: #000000;
  padding: 10px;
  text-align: center;
}
<div id="parent">
  <div id="child">I'm the child and I'm horizontally centered! My daddy is a greyish div dude!</div>
</div>

Run the code to see how it works, also there are 2 important things you shoyuldn't forget in your CSS when you try to center this way: margin: 0 auto; that make it the div center as wanted, plus don't forget width of the child, otherwise it won't get centered as expected!

you can use 1 line of code.
Just text-align:center
here's example :

#inner {
  text-align:center;
  }
<div id="outer" style="width:100%">  
  <div id="inner"><button>hello</button></div>
</div>

Text-align: center

Applying text-align: center the inline contents are centered within the line box. However since the inner div has by default width: 100% you have to set a specific width or use one of the following:

#inner {
  display: inline-block;
}

#outer {
  text-align: center;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>


Margin: 0 auto

Using margin: 0 auto is another option and it is more suitable for older browsers compatibility. It works together with display: table.

#inner {
  display: table;
  margin: 0 auto;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>


Flexbox

display: flex behaves like a block element and lays out its content according to the flexbox model. It works with justify-content: center.

Please note: Flexbox is compatible with most of the browsers but not all. See here for a complete and up to date list of browsers compatibility.

#inner {
  display: inline-block;
}

#outer {
  display: flex;
  justify-content: center;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>


Transform

transform: translate lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed. To center horizontally it require position: absolute and left: 50%.

#inner {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0%);
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>


<center> (Deprecated)

The tag <center> is the HTML alternative to text-align: center. It works on older browsers and most of the new ones but it is not considered a good practice since this feature is obsolete and has been removed from the Web standards.

#inner {
  display: inline-block;
}
<div id="outer">
  <center>
    <div id="inner">Foo foo</div>
  </center>
</div>

I'm sorry but this baby from the 1990's just WORKED for me:

<div id="outer">  
  <center>Foo foo</center>
</div>

Am I going to hell for this sin?

1 upvote
  flag
The <center> tag is deprecated since HTML4, like Idra explained in comments – Garric15
upvote
  flag
@Garric15 I'm just trying to encourage some ppl who maybe keep losing hours and hours of work for solving a very tiny problem just because they don't want to use a deprecated tag like <center> despite it keeps working perfectly fine in some cases. The <center> tag was deprecated but nothing as simple and effective as it came to replace it decently in all cases. – Heitor

you can use the following link

https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview

.outer{
      display: table;
      width: 100%;
      height: 100%;
}
.inner {
    vertical-align: middle;
}

refer this https://v4-alpha.getbootstrap.com/examples/cover/

You can add this code:

#inner {
  width: 90%;
  margin: 0 auto;
  text-align:center;
}
<div id="outer">  
  <div id="inner">Foo foo</div>
</div>

Center a div in a div

.outer {
  display: -webkit-flex;
  display: flex;

  //-webkit-justify-content: center;							
  //justify-content: center;
  
  //align-items: center;

  width: 100%;
  height: 100px;
  background-color: lightgrey;
}

.inner {
  background-color: cornflowerblue;
  padding: 2rem;
  margin: auto;  
  
  //align-self: center;						
}
<div class="outer">  
  <div class="inner">Foo foo</div>
</div>

upvote
  flag
Thank you for your answer! If you think that your answer contributes something valuable to the question, be sure to further explain your code and what it does and why it works, thanks! – Ian H.
1 upvote
  flag
this worked for me. most of the time display block then margin auto for inner div doesnt work but with the display flex in outer div worked great. thanks alot. I havent tried the display flex before. – livefreeor
upvote
  flag
me too. using display table also great. my another answer. //allinonescript.com/questions/5703552/… – antelove

After researching I found this solution which I am sharing with you all, hoping it helps you in so many situation as It helped me.

We could use the next css´s class which allow center vertically and horizontally any element agaisnt its parent:

.centerElement{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div id="parent">
  <div class="child"></div>
</div>

style:

#parent {
   display: flex;
   justify-content: center;
}

if you want to center it horizontally you should write below

#parent {
   display: flex;
   justify-content: center;
   align-items: center;
}

I wanted to answer this as I noticed no body mentioned the calc method, the usage is for the div you're centering, if you know its width, let's say it's 1200px, go for:

.container {
    width:1200px;
    margin-left: calc(50% - 600px);
}

So basically it'll add a left margin of 50% minus half the known width, hope this helps someone.

Use this code

<div id="outer">  
      <div id="inner">Foo foo</div>
    </div>

#inner {
  width: 50%;
  margin: 0 auto;
  text-align: center;
}
<style>
  #outer{
    text-align:center;
    width:100%;
  }
  #inner{
    text-align:center;
  }
</style>

You can do different way see below examples

1. First Method 
#outer {
   text-align: center;
   width: 100%;
}
#inner {
   display: inline-block;
}


2. Second method
#outer {
  position: relative;
  overflow:hidden;
}
.centered {
   position: absolute;
   left: 50%;
}

I hope this answer is useful for you.

After reading carefully all the answers here is another way to center horizontally using flexbox and without specifying any width to inner container. The idea is to use pseudo elements that will push the inner content from the right and the left.

Using flex:1 on pseudo element will make them fill the remaining spaces and take equal size and the inner container will get centered.

.container {
  display: flex;
  border: 1px solid;
}

.container:before,
.container:after {
  content: "";
  flex: 1;
}

.inner {
  border: 1px solid red;
  padding:5px;
}
<div class="container">
  <div class="inner">
    Foo content
  </div>
</div>

We can also consider the same situation for vertical alignment by simply changing the direction of flex to column :

.container {
  display: flex;
  flex-direction:column;
  border: 1px solid;
  min-height:200px;
}

.container:before,
.container:after {
  content: "";
  flex: 1;
}

.inner {
  border: 1px solid red;
  padding:5px;
}
<div class="container">
  <div class="inner">
    Foo content
  </div>
</div>

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