How to horizontally center a
in another
?

Lukas Source

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>
htmlcssalignmentvertical-alignmentcentering

Answers

answered 10 years ago Justin Poliey #1

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>

answered 10 years ago gizmo #2

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

answered 9 years ago Sneakyness #3

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.

answered 8 years ago Alfred #4

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.

answered 7 years ago James Moberg #5

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>

answered 7 years ago nuno_cruz #6

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/

answered 7 years ago neoneye #7

CSS3's box-align property

#outer {
    width:100%;
    height:100%;
    display:box;
    box-orient:horizontal;
    box-pack:center;
    box-align:center;
}

answered 6 years ago Salman Abbas #8

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

answered 6 years ago ch2o #9

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.

answered 6 years ago Konga Raju #10

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:

answered 6 years ago Ray #11

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

answered 5 years ago william44isme #12

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.

answered 5 years ago Danield #13

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.

answered 5 years ago BenjaminRH #14

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.

answered 5 years ago aamirha #15

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>

answered 5 years ago Ankit Jain #16

This is my answer.

#outerDiv {
  width: 500px;
}

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

answered 5 years ago Tom Maton #17

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.

answered 5 years ago Rajesh #18

How about the below CSS for #inner div:

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

I mostly use this CSS to center divs.

answered 5 years ago Kenneth Palaganas #19

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;

answered 5 years ago Willem de Wit #20

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

answered 5 years ago Josh Mc #21

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.

answered 5 years ago user1817972 #22

Try playing around with

margin: 0 auto;

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

text-align: center;

answered 5 years ago Pnsadeghy #23

One option existed that I found:

Everybody says to use:

margin: auto 0;

But there is another option. Set this property for the parent div. It works perfectly anytime:

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

answered 5 years ago user2952495 #24

<center>

I am spoiled with the most simple center known?

</center>

answered 5 years ago Lalit Kumar #25

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 horizontally. */
  line-height: 120px; /* For text alignment to center vertically. */
}
<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 content must be like this example on fiddle.

The HTML content 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.

answered 5 years ago Salman A #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%;
}

answered 5 years ago caniz #27

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

answered 5 years ago Miguel Leite #28

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

answered 5 years ago uSeRnAmEhAhAhAhAhA #29

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

answered 4 years ago iamnotsam #30

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.

answered 4 years ago hossein ketabi #31

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

answered 4 years ago joan16v #32

The easiest way:

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

answered 4 years ago Gerald Goshorn #33

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>

answered 4 years ago sarath #34

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

answered 4 years ago user3968801 #35

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.

answered 4 years ago Cees Timmerman #36

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.

answered 4 years ago Kilian Stinson #37

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.

answered 3 years ago anand jothi #38

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

answered 3 years ago Ajay Gupta #39

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

answered 3 years ago Majid Sadr #40

#outer {postion: relative}
#inner {
    width: 100px; 
    height: 40px; 
    position: absolute;
    top: 50%;
    margin-top:-20px; /* Half of your Height */
}

answered 3 years ago Justin Munce #41

Depending on your circumstances, the simplest solution could be:

margin:0 auto; float:none;

answered 3 years ago BANTIMATHUR #42

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

answered 3 years ago Sajid #43

I am sharing this answer for the designers who want to align their content both horizontally and vertically. Or you may say in the center of the web page. Please go to this site to download the file.

CSS Code

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

answered 3 years ago hossein ghaem #44

The best way is using table-cell display (inner) that come exactly after a div with the display table (outer) and set vertical align for the 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>

answered 3 years ago John Slegers #45

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

answered 2 years ago Gaurav Aggarwal #46

It is so simple.

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

CSS

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

answered 2 years ago Qmr #47

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

answered 2 years ago Mardok #48

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

answered 2 years ago Fahad Uddin #49

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.

answered 2 years ago Friend #50

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/

answered 2 years ago Billal Begueradj #51

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.

answered 2 years ago Saurav Rastogi #52

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>

answered 2 years ago Mr.Pandya #53

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

answered 2 years ago amit bende #54

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

answered 2 years ago Cyan Baltazar #55

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/

answered 2 years ago Dream Hunter #56

It's possible using CSS 3 flexbox. You have two methods when using flex box.

  1. Set the 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 the 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>

answered 2 years ago User #57

Add CSS to your inner div. Set margin: 0 auto and set its 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.

answered 2 years ago Abdul Ghaffar #58

CSS

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

HTML

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

answered 2 years ago sneha #59

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

answered 2 years ago Faizal Munna #60

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

answered 2 years ago Sankar #61

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>

answered 2 years ago Legends #62

CSS 3:

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>

answered 1 year ago Sandesh Damkondwar #63

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

answered 1 year ago Agu Dondo #64

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

answered 1 year ago Faizal #65

Use the below code.

HTML

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

CSS

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

answered 1 year ago Alireza #66

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!

answered 1 year ago Yahya Essam #67

You can use one line of code, just text-align:center.

Here's an example:

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

answered 1 year ago Paolo Forgia #68

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>

answered 1 year ago Heitor #69

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?

answered 1 year ago sibaspage #70

You can use the link https://plnkr.co/edit/MQD5QHJe5oUVKEvHCz8p?p=preview

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

Refer to https://v4-alpha.getbootstrap.com/examples/cover/

answered 1 year ago Rafiqul Islam #71

You can add this code:

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

answered 12 months ago antelove #72

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>

answered 12 months ago Elias MP #73

We could use the next CSS's class which allow center vertically and horizontally any element against its parent:

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

answered 12 months ago Руслан #74

Use:

<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 as below:

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

answered 12 months ago serdarsenay #75

I wanted to answer this as I noticed nobody mentioned the calc method. The usage is for the div you're centering, if you know its width, let's say it's 1200 pixels, 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.

answered 11 months ago Husain Ahmed #76

Use this code:

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

#inner {
  width: 50%;
  margin: 0 auto;
  text-align: center;
}

answered 11 months ago SUNIL KUMAR E.U #77

Use:

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

answered 10 months ago Gaurang Sondagar #78

You can do it in a different way. See the 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%;
}

answered 9 months ago Temani Afif #79

After carefully reading 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>

answered 8 months ago Anu #80

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

answered 8 months ago Anu #81

The main attributes for centering the div are margin: auto and width: according to requirements:

.DivCenter{
    width: 50%;
    margin: auto;
    border: 3px solid #000;
    padding: 10px;
}

answered 6 months ago Shivam Chhetri #82

This centralizes your inner div horizontally and vertically:

#outer{
    display: flex;
}
#inner{
    margin: auto;
}

For only horizontal align, change

margin: 0 auto;

and for vertical, change

margin: auto 0;

answered 3 months ago Milan Panigrahi #83

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.

answered 3 months ago TitusMix #84

This may also work(not using css):

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

answered 2 months ago MANGESH SUPE #85

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

answered 1 month ago Jaison #86

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

answered 1 month ago Galarist #87

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

answered 2 weeks ago Mark Salvania #88

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>

answered 2 weeks ago drewkiimon #89

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>

answered 2 weeks ago Morteza Sadri #90

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.

comments powered by Disqus