By Lukas


2008-09-22 12:27:57 8 Comments

How can I horizontally center a <div> within another <div> using CSS?

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

30 comments

@Ady Ngom 2019-02-12 02:47:31

As of 2019 since this question still gets a lot of hits a very simple and cross browser answer to horizontal center is to apply this rule to the parent element:

.parentBox {
 display: flex;
 justify-content: center
}

@Mohammed Rabiulla RABI 2018-11-14 09:25:59

div{
   width:100px;
   height:100px;
   margin:0 auto;
  }

for normal thing if you using div static way

if you want div to be in centered when div is absolute to its parent here is example:

.parentdiv{
   position:relative;
   height:500px;
}

.child_div{
   position:absolute;
   height:200px;
   width:500px;
   left:0;
   right:0;
   margin:0 auto;
}

@iorgu 2018-12-29 21:02:52

I found similar with margin-left, but can be left as well.

#inner{
    width: 100%;
    max-width: 65px; /*to adapt to screen width. Can be whatever you want*/
    left: 65px; /*this has to be approximately the same as the max-width*/
}

@Temani Afif 2017-12-19 11:05:06

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>

@Fatemeh Khosravi Farsani 2018-11-25 08:40:10

this worked for me:

   #inner {
    position: absolute;
    margin: 0 auto;
    left: 0;
    width: 7%;
    right: 0;
}

In this code, you to be determine width of element.

@Morteza Sadri 2018-09-10 23:06:24

You can do it buy using flex-box witch is a good technique these days. For using flex-box you should give display: flex; and align-items: center; to your parent or #outer div element. The code should be like this :

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

This should center your child or #inner div horizontally. But you can't actually see any changes. Because our #outer div has no height or in other words, its height is set to auto so it has the same height as all of its child elements. So after a little of visual styling, the result code should be like this :

#outer {
  height: 500px;
  display: flex;
  align-items: center;
  background-color: blue;
}

#inner {
  height: 100px;
  background: yellow;
}
<div id="outer">  
  <div id="inner">Foo foo</div>
</div>

You can see #inner div is now centered. Flex-box is the new method of positioning elements in horizontal or vertical stacks with CSS and it's got 96% of global browsers compatibility. So you are free to use it and if you want to find out more about Flex-box visit CSS-Tricks article, that is the best place to learn using Flex-box in my opinion.

@Mark Salvania 2018-09-07 21:55:36

This will surely center your #inner both horizontally and vertically. This is also compatible in all browsers. I just added extra styling just to show how it is centered.

#outer {
  background: black;
  position: relative;
  width:150px;
  height:150px;
}

#inner { 
  background:white;
  position: absolute;
  left:50%;
  top: 50%;
  transform: translate(-50%,-50%);
  -webkit-transform: translate(-50%,-50%);
  -moz-transform: translate(-50%,-50%); 
  -o-transform: translate(-50%,-50%);
} 
<div id="outer">  
  <div id="inner">Foo foo</div>
</div>

But of course if you only want it horizontally aligned, This may help you.

#outer {
  background: black;
  position: relative;
  width:150px;
  height:150px;
}

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

@drewkiimon 2018-09-07 21:56:14

One of the easiest ways you can do it is by using display: flex. The outer div just needs to have display flex, and the inner needs margin: 0 auto to make it centered horizontally.

To center vertically and just center a div within another div, please look at the comments of the .inner class below

.wrapper {
  display: flex;
  /* Adding whatever height & width we want */
  height: 300px;
  width: 300px;
  /* Just so you can see it is centered */
  background: peachpuff;
}

.inner {
  /* center horizontally */
  margin: 0 auto;
  /* center vertically */
  /* margin: auto 0; */
  /* center */
  /* margin: 0 auto; */
}
<div class="wrapper">
  <div class="inner">
    I am horizontally!
  </div>
</div>

@Milan Panigrahi 2018-06-10 15:53:54

You can use display: flex for your outer div and to horizontally center you have to add justify-content: center

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

or you can visit w3schools - CSS flex Property for more ideas.

@Galarist 2018-08-14 14:49:52

#outer {
  width: 160px;
  padding: 5px;
  border-style: solid;
  border-width: thin;
  display: block;
}

#inner {
  margin: auto;
  background-color: lightblue;
  border-style: solid;
  border-width: thin;
  width: 80px;
  padding: 10px;
  text-align: center;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

@Jaison 2018-08-07 10:01:52

The best I have used in my various projects is

<div class="outer">
    <div class="inner"></div>
</div>
.outer{
  width: 500px;
  height: 500px;
  position: relative;
  background: yellow;
}
.inner{
  width: 100px;
  height: 100px;
  background:red;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

fiddle link

@MANGESH SUPE 2018-07-15 15:00:52

<!DOCTYPE html>
<html>
  <head>
    <title>Center</title>
    <style>
    .outer{
          text-align: center;
           }
    .inner{
          width: 500px; 
          margin: 0 auto; 
          background: brown; 
          color: red;
    }
 
</style>

  </head>

  <body>

    <div class="outer">
      <div class="inner">This DIV is centered</div>
    </div>

  </body>
</html>

plz try this will work without html center tag

@TitusMix 2018-06-22 01:32:50

This may also work(not using css):

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

@sarath 2014-09-20 07:22:04

If anyone would like a jQuery solution 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;");
});

@Salman A 2014-01-17 18:18:26

If width of the content is unknown you can use the following method. Suppose we have these two elements:

  • .outer -- full width
  • .inner -- no width set (but a max-width could be specified)

Suppose the computed width of the elements are 1000px and 300px respectively. Proceed as follows:

  1. Wrap .inner inside .center-helper
  2. Make .center-helper an inline block; it becomes the same size as .inner making it 300px wide.
  3. Push .center-helper 50% right relative to its parent; this places its left at 500px wrt. outer.
  4. Push .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 to prevent horizontal scrollbar.

Demo:

body {
  font: medium sans-serif;
}

.outer {
  overflow: hidden;
  background-color: papayawhip;
}

.center-helper {
  display: inline-block;
  position: relative;
  left: 50%;
  background-color: burlywood;
}

.inner {
  display: inline-block;
  position: relative;
  left: -50%;
  background-color: wheat;
}
<div class="outer">
  <div class="center-helper">
    <div class="inner">
      <h1>A div with no defined width</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br>
          Duis condimentum sem non turpis consectetur blandit.<br>
          Donec dictum risus id orci ornare tempor.<br>
          Proin pharetra augue a lorem elementum molestie.<br>
          Nunc nec justo sit amet nisi tempor viverra sit amet a ipsum.</p>
    </div>
  </div>
</div>

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

@Danield 2013-04-22 10:32:07

Some posters have mentioned the CSS 3 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 CSS 3 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.

@Konga Raju 2013-09-06 10:18:39

what do you mean by "syntax is outdated", is it deprecated?

@cimmanon 2013-10-01 20:33:33

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): stackoverflow.com/questions/15662578/…

@Vern Jensen 2016-06-29 02:50:17

This worked for me in Chrome when Justin Poliey's version didn't.

@Wouter Vanherck 2017-03-22 12:04:47

Isn't the "justify-content: center;" for the vertical alignment and the "align-items: center;" for the horizontal alignment?

@Danield 2017-03-22 12:29:34

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

@Ray 2013-03-14 15:00:00

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 CSS 2 support. Unfortunately, Internet Explorer 5/Windows 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? Internet Explorer 5/Windows 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 Internet Explorer 5/Windows.

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 Internet Explorer 5/Windows 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

@clickbait 2015-06-12 23:50:25

That's not centering the div, that's centering the text.

@Kumar 2018-06-04 04:08:20

Its not a good solutions

@Konga Raju 2012-08-30 12:05:25

The best approaches are 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 the box model is the best approach:

@Tareq 2012-11-12 06:30:08

it also works for me when inner div have float: left;

@cimmanon 2013-04-24 18:51:58

Make sure you read this answer first before you go about implementing this solution.

@Joseph Hansen 2015-07-23 15:59:08

Safari, as of now, still requires -webkit flags for flexbox (display: -webkit-flex; and -webkit-align-items: center; and -webkit-justify-content: center;)

@ch2o 2012-05-31 15:32:44

For Firefox and Chrome:

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

For Internet Explorer, Firefox, and 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 it is necessary in Internet Explorer Quirks Mode for legacy browsers support.

@Touhid Rahman 2013-05-23 05:29:18

There is no need for text-align property. It's completely un-necessary.

@heytools 2017-11-04 02:02:51

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)

@Sneakyness 2009-07-24 22:00:04

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.

@BANTIMATHUR 2015-12-23 09:39:26

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. */;
}

@Ajay Gupta 2015-09-01 10:13:16

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

@Kilian Stinson 2015-03-12 14:01:38

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

#outer {
  position: relative;
}

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

  transform: translateX(-50%);
}

The trick is 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 is on Mozilla Developer Network.

@Skippy le Grand Gourou 2015-09-02 13:48:49

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

@Cees Timmerman 2015-01-15 14:31:34

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>

It 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 the HTML body and enjoy.

@user3968801 2014-09-27 08:29:03

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.

@Gerald Goshorn 2014-09-19 21:26:23

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>

@joan16v 2014-08-22 12:10:48

The easiest way:

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

@Michael Terry 2015-02-05 21:06:57

As your fiddle notes, #inner has to have a width set on it.

@hossein ketabi 2014-08-13 13:20:22

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

@iamnotsam 2014-05-17 18:38:48

Centering a div of unknown height and width

Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet Explorer 10, 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.

@Miguel Leite 2014-02-11 15:51:03

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

Related Questions

Sponsored Content

41 Answered Questions

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

24 Answered Questions

[SOLVED] Vertically centering a div inside another div

  • 2011-06-27 08:22:03
  • user700284
  • 525007 View
  • 481 Score
  • 24 Answer
  • Tags:   html css html5 css3

38 Answered Questions

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

31 Answered Questions

[SOLVED] Center a column using Twitter Bootstrap 3

18 Answered Questions

[SOLVED] Center image horizontally within a div

  • 2012-06-12 00:40:57
  • Jacob Windsor
  • 638367 View
  • 315 Score
  • 18 Answer
  • Tags:   html css

10 Answered Questions

[SOLVED] Flexbox: center horizontally and vertically

40 Answered Questions

[SOLVED] How to disable text selection highlighting?

33 Answered Questions

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

36 Answered Questions

[SOLVED] How to make an image center (vertically & horizontally) inside a bigger div

  • 2008-12-23 04:32:38
  • Shameem
  • 887937 View
  • 382 Score
  • 36 Answer
  • Tags:   html css

26 Answered Questions

[SOLVED] Set cellpadding and cellspacing in CSS?

Sponsored Content