How to horizontally center an element

Created 22.09.2008 12:27
Viewed 4.32M times
4611 votes

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

<div id="outer">
  <div id="inner">Foo foo</div>
</div>
6
Comments
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. by Jony, 07.11.2017 08:22
Joma Tech brought me here by Barbu Barbu, 01.04.2020 18:56
@Barbu Barbu: In what way? In what context? by Peter Mortensen, 09.05.2020 06:34
youtu.be/kZC12U6EhTc?t=202 by Barbu Barbu, 10.05.2020 07:33
JomaTech brought me here. by Shubham Gaikwad, 08.01.2021 17:06
Try this stackoverflow.com/a/67390020/11384233 by Tharindu Lakshan, 04.05.2021 18:18
Show remaining 1 comments
Answers 50
20
5070

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 Internet Explorer 8 (and later), 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;
  border: 1px solid black;
}

#outer {
  border: 1px solid red;
  width:100%
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>


EDIT

With flexbox it is very easy to style the div horizontally and vertically centered.

#inner {  
  border: 1px solid black;
}

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

To align the div vertically centered, use the property align-items: center.

22.09.2008 12:29
Comments
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 :) by Nicolas Guillaume, 23.06.2010 12:36
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;} by pepkin88, 08.01.2011 21:00
You have to use the !DOCTYPE tag on your html page to make it work well on IE. by Fabio, 28.01.2012 14:23
can someone explain how display:table works? why do elements with this styling applied automatically shrink to the size of the inner elements by Zhanger, 19.08.2013 17:20
Note that it may be necessary to add "float:none;" for the #inner. by Mert Mertce, 27.09.2013 08:30
@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. by SpYk3HH, 20.01.2014 21:01
You also set the top and bottom margins to 0, which is unrelated. Better putting margin-left: auto; margin-right: auto I think. by Emmanuel Touzery, 08.02.2014 22:45
To support mobile browsers, I do not recommend using width: 50%. Use something like max-width: 300px instead. by rybo111, 14.05.2014 09:21
This works fine on Chrome but does NOT support mobile browsers like Safari. by Sam Su, 19.06.2014 11:40
CSS margin:0 auto will not work when the div has position property other than relative, like in the case of position:absolute by sarath, 02.02.2016 12:37
Why do we need to specify the width ? by HelloWorldNoMore, 21.04.2016 18:43
Not necessarily margin:0 auto: it can be margin: <whatever_vertical_margin_you_need> auto second being the horizontal margin. by YakovL, 03.05.2016 19:07
Why is text-align: center; obsolete? by Winter, 05.09.2016 21:17
This is far from being a perfect solution as anything inside the inner DIV must be displayed as a table's element by Billal Begueradj, 04.11.2016 19:40
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 by amachree tamunoemi, 20.04.2017 02:07
Why this doesn't work if inner element is button and not a div. by Saurabh Tiwari, 27.07.2017 19:16
Because "input" is inline element and must be centered by "text-align: center". by Simon Logic, 01.08.2017 19:02
@Winter text-align: center; is not obsolete by simon, 04.11.2019 18:03
@amachreetamunoemi do you think that? then could you ask with a better solution by simon, 04.11.2019 18:04
display: flex; justify-content: center; this work perfect by M.Idrish, 05.11.2020 07:57
Show remaining 15 comments
3
1319

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.

20.01.2011 22:55
Comments
@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. by Doug McLean, 12.11.2015 09:21
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. by pmoleri, 18.11.2016 21:52
but isn't the question related to centering a div entirely and not just the text? can text-align be used to center align divs? or is it just for text? by Ashwin K Joseph, 16.08.2020 18:48
3
413

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%;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

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:

30.08.2012 12:05
Comments
Make sure you read this answer first before you go about implementing this solution. by cimmanon, 24.04.2013 18:51
Safari, as of now, still requires -webkit flags for flexbox (display: -webkit-flex; and -webkit-align-items: center; and -webkit-justify-content: center;) by Joseph Hansen, 23.07.2015 15:59
I always think that use lots code is bad practice for example with this code I center my div: display: table; margin: auto; simple and easy by simon, 04.11.2019 18:11
3
270

Suppose that your div is 200 pixels 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/

With CSS calc(), the code can get even simpler:


.centered {
  width: 200px;
  position: absolute;
  left: calc(50% - 100px);
}

The principle is still the same; put the item in the middle and compensate for the width.

01.12.2011 19:52
Comments
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. by Aloso, 30.12.2015 04:02
margin-left: auto; margin-right: auto; centres a block level element by killscreen, 10.11.2017 19:15
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). by killscreen, 10.11.2017 19:16
3
249

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

The 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 resize your screen.

11.09.2013 11:32
Comments
+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. by stvnrynlds, 16.12.2013 18:27
You cannot use padding within the div, but if you want to give the illusion use a border of the same color. by Squirrl, 09.07.2014 11:45
I think for this method to work, you need to set the with and height of inner div by Nicolas S.Xu, 29.11.2015 21:39
5
235

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.

22.04.2013 10:32
Comments
what do you mean by "syntax is outdated", is it deprecated? by kongaraju, 06.09.2013 10:18
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/… by cimmanon, 01.10.2013 20:33
This worked for me in Chrome when Justin Poliey's version didn't. by Vern Jensen, 29.06.2016 02:50
Isn't the "justify-content: center;" for the vertical alignment and the "align-items: center;" for the horizontal alignment? by Wouter Vanherck, 22.03.2017 12:04
@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. by Danield, 22.03.2017 12:29
2
155

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;
}
12.05.2012 23:45
Comments
same requirements as display:inline-block too (quirksmode.org/css/display.html) by montrealmike, 11.09.2012 15:09
I used this, too, but I've never encountered display: table; before. What does it do? by Matt Cremeens, 31.07.2017 11:25
2
120

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%;
  transform: translate(-50%, -50%);
}
<div class="content">This works with any content</div>

Tinker with it further on Codepen or on JSBin.

17.05.2014 18:38
Comments
This is the only one that works for perfect centering and will remain centered even after the contents in the div are modified. by Phani Rithvij, 04.07.2020 11:20
It's a nice trick, but there is a little caveat. If the element has inline content that's wider than 50% of the parent's width, then the extra 50% offset from the left will extrapolate the parent's width, breaking the content to the next lines to avoid overflow. But it's possible to keep the content inline by setting in the centered element the white-space attribute to nowrap. Try that in this JSFiddle. by Felypp Oliveira, 29.12.2020 12:47
3
104

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

22.09.2008 12:30
Comments
and if you don't know the width? Say because the content is dynamic? by gman, 02.06.2011 15:45
max-width? what about that? by User, 17.03.2018 22:32
I use width: fit-content; and margin: 0 auto. I think this can work with unknown width. by Rick, 15.10.2019 04:15
0
105

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.

24.07.2009 22:00
1
97

CSS 3's box-align property

#outer {
    width: 100%;
    height: 100%;
    display: box;
    box-orient: horizontal;
    box-pack: center;
    box-align: center;
}
11.03.2012 13:37
Comments
Make sure you read this answer first before you go about implementing this solution. by cimmanon, 24.04.2013 18:52
0
73

I recently had to center a "hidden" div (i.e., display:none;) that had a tabled form within it that needed to be centered on the page. I wrote the following jQuery code to display the hidden div and then update the CSS content 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 necessary to display.)

NOTE: I'm sharing this code, because Google brought me to this Stack Overflow solution and everything would have worked except that hidden elements don't have any width and 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>

23.06.2011 21:42
1
70

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.

07.04.2013 08:22
Comments
This may not work if you have other divs below the centered div. by NoChance, 26.07.2018 07:59
2
64

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.

31.05.2012 15:32
Comments
There is no need for text-align property. It's completely un-necessary. by Touhid Rahman, 23.05.2013 05:29
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) by heytools, 04.11.2017 02:02
0
60

Use:

#outerDiv {
  width: 500px;
}

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

19.07.2013 10:21
1
57

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.

12.03.2015 14:01
Comments
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); by Skippy le Grand Gourou, 02.09.2015 13:48
0
52

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 than 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;
}
25.10.2013 11:53
1
47

I recently found an approach:

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

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

Both elements must be the same width to function correctly.

27.05.2013 16:12
Comments
Just set this rule for #inner only: #inner { position:relative; left:50%; transform:translateX(-50%); }. This works for any width. by Jose Rui Santos, 24.11.2015 10:30
0
42

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.

04.12.2013 07:30
0
37

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!

19.02.2016 16:57
2
33

The easiest way:

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

22.08.2014 12:10
Comments
As your fiddle notes, #inner has to have a width set on it. by Michael Terry, 05.02.2015 21:06
#outer doesn't need any width:100%; as the <div> by default always has width:100%. and text-align:center is also not a necessary at all. by Mobarak Ali, 06.05.2019 22:57
0
31

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 1000 pixels and 300 pixels 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 300 pixels wide.
  3. Push .center-helper 50% right relative to its parent; this places its left at 500 pixels wrt. outer.
  4. Push .inner 50% left relative to its parent; this places its left at -150 pixels wrt. center helper which means its left is at 500 - 150 = 350 pixels 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>

17.01.2014 18:18
0
28

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;

14.10.2013 12:09
0
30

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 display: flex not working on Internet Explorer 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>

09.06.2017 08:34
1
26

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 % );
}
28.01.2014 09:55
Comments
That centers it vertically. by Michael Terry, 06.02.2015 00:24
0
27

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;
}
03.04.2017 20:12
0
23

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);
  })
});
11.02.2014 15:51
0
25

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.

10.06.2018 15:53
1
24

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.

23.09.2016 06:49
Comments
in regards to edit records this person answered first on the page. Upvoting. by CodeToLife, 22.06.2020 13:18
5
21

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 */
}
16.11.2013 19:56
Comments
text-align work for text alignment in its container not for its container to its parent. by Lalit Kumar Maurya, 04.12.2013 07:32
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 by Pnsadeghy, 04.12.2013 08:35
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!!!! by Lalit Kumar Maurya, 04.12.2013 09:23
See this example jsfiddle.net/uCdPK/2 and tell me what do you think about it!!!!! by Lalit Kumar Maurya, 04.12.2013 10:03
this works great. no need for a #inner . by Miguel Silva, 28.03.2021 19:14
0
18

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;");
});
20.09.2014 07:22
1
17

Try playing around with

margin: 0 auto;

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

text-align: center;
05.11.2013 15:21
Comments
text-align work for text alignment in its container not for its container to its parent. by Lalit Kumar Maurya, 04.12.2013 07:33
1
17

You can just simply use Flexbox like this:

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

Apply Autoprefixer for all browser support:

#outer {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    width: 100%;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center
}

Or else

Use transform:

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

With Autoprefixer:

#inner {
    position: absolute;
    left: 50%;
    -webkit-transform: translate(-50%);
    -ms-transform:     translate(-50%);
    transform:         translate(-50%)
}
04.04.2019 11:59
Comments
Related: Will CSS 3 still allow omitting final semicolons? by Peter Mortensen, 19.11.2019 12:22
0
16

We can use Flexbox to achieve this really easily:

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

Center a div inside a div horizontally:

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

Enter image description here

Center a div inside a div vertically:

#outer {
    display: flex;
    align-items: center;
}

Enter image description here

And, to completely middle the div vertically and horizontally:

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

Enter image description here

12.07.2019 18:09
0
15

Just add this CSS content into your CSS file. It will automatically center the content.

Align horizontally to center in CSS:

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

Align-vertically + horizontal to center in CSS:

#outer {
    display: flex;
    justify-content: center;
    align-items: center;
}
06.01.2020 06:44
0
13

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
}
12.02.2019 02:47
0
9

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

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

A 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 + Internet Explorer 8. 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.

31.10.2013 19:56
0
7

Use the below CSS content for #inner div:

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

I mostly use this CSS content to center divs.

01.10.2013 18:14
1
7
#inner {
    width: 50%;
    margin: 0 auto;
}
15.05.2015 10:26
Comments
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. by Rapnar, 20.10.2015 17:49
0
8

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>

11.03.2017 14:14
2
-4
<center>

I am spoiled with the most simple center known?

</center>
02.12.2013 22:48
Comments
This worked for me and am not sure why it isn't the answer. Can someone explain what is wrong with this? by DaveWalley, 20.01.2014 04:26
@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 by Idra, 26.01.2014 13:42
0
7

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>

01.11.2016 13:41
0
6

It's possible using CSS 3 Flexbox. You have two methods when using Flexbox.

  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>

13.01.2017 12:13
1
5

Make it simple!

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

26.03.2019 15:27
Comments
An explanation would be in order. by Peter Mortensen, 11.05.2020 21:44
0
5

This is the best example to horizontally center a <div>

#outer {
    display: flex;
    align-items: center;
    justify-content: center;
}
<!DOCTYPE html>
<html>
    <head>

    </head>

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

23.11.2019 10:54
2
3

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

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

Am I going to hell for this sin?

22.07.2017 06:42
Comments
The <center> tag is deprecated since HTML4, like Idra explained in comments by Garric15, 25.07.2017 14:51
@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. by Heitor, 26.07.2017 15:17
0
4

I used Flexbox or CSS grid

  1. Flexbox

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

  2. CSS grid

    #outer {
        display: inline-grid;
        grid-template-rows: 100px 100px 100px;
        grid-template-columns: 100px 100px 100px;
        grid-gap: 3px;
    }

You can solve the issue in many ways.

19.02.2020 13:12
1
-9

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

14.03.2013 15:00
Comments
That's not centering the div, that's centering the text. by clickbait, 12.06.2015 23:50
0
4

You can do it by using Flexbox which is a good technique these days.

For using Flexbox 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. Flexbox 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 Flexbox visit CSS-Tricks article. That is the best place to learn using Flexbox in my opinion.

10.09.2018 23:06