5037

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

<div id="outer">
  <div id="inner">Foo foo</div>
</div>
Lukas
  • 9,476
  • 4
  • 20
  • 14
  • 36
    Of those great answers, I just want to highlight that you must give "#inner" a "width", or it will be "100%", and you can't tell if it's already centered. – Jony Nov 07 '17 at 08:22
  • 1
    `display:flex;` is the easiest to remember (Chrome gives you guides in DevTools) and supports centering on both axes. – Akshay K Nair Feb 10 '22 at 05:39

131 Answers131

5486

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

#inner {  
  border: 0.05em solid black;
}

#outer {
  border: 0.05em 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.


Other Solutions

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>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Justin Poliey
  • 16,289
  • 7
  • 37
  • 48
  • 23
    You also set the top and bottom margins to 0, which is unrelated. Better putting `margin-left: auto; margin-right: auto` I think. – Emmanuel Touzery Feb 08 '14 at 22:45
  • 1
    To support mobile browsers, I do not recommend using `width: 50%`. Use something like `max-width: 300px` instead. – rybo111 May 14 '14 at 09:21
  • CSS `margin:0 auto` will not work when the div has `position` property other than `relative`, like in the case of `position:absolute` – sarath Feb 02 '16 at 12:37
  • 19
    Not necessarily `margin:0 auto`: it can be `margin: auto` second being the horizontal margin. – YakovL May 03 '16 at 19:07
  • 2
    voted most but not a better solution. the best way to do this is to use the combination of div and span tag, block css property and cross browser inline-block, and text center will do the simple magin – amachree tamunoemi Apr 20 '17 at 02:07
  • Why this doesn't work if inner element is `button` and not a `div`. – Saurabh Tiwari Jul 27 '17 at 19:16
  • 1
    Because "input" is inline element and must be centered by "text-align: center". – Simon Logic Aug 01 '17 at 19:02
  • @amachreetamunoemi do you think that? then could you ask with a better solution – simon Nov 04 '19 at 18:04
  • display: flex; justify-content: center; this work perfect – M.Idrish Nov 05 '20 at 07:57
  • This is perfect ... I had to add "position: unset" because of an inherited attribute, but otherwise, perfect! – user3481644 Nov 22 '21 at 20:45
  • Unbelievable how the most voted solution does not work to align the item vertically in Microsoft Edge in 2023. – Sergey Feb 20 '23 at 14:30
1403

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.

Martin Lindgren
  • 374
  • 2
  • 14
Alfred
  • 7,071
  • 4
  • 27
  • 35
  • 18
    @SabaAhang the correct syntax for that would be `float: none;` and is probably only needed because #inner has inherited a `float` of either `left` or `right` from somewhere else in your CSS. – Doug McLean Nov 12 '15 at 09:21
  • 11
    This is a nice solution. Just keep in mind that inner will inherit `text-align` so you may want to set inner's `text-align` to `initial` or some other value. – pmoleri Nov 18 '16 at 21:52
450

The best approaches are with CSS3.

The old box model (deprecated)

display: box and its properties box-pack, box-align, box-orient, box-direction etc. have been replaced by flexbox. While they may still work, they are not recommended to be used in production.

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

The modern box model with Flexbox

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

PeterJames
  • 1,137
  • 1
  • 9
  • 17
kongaraju
  • 9,344
  • 11
  • 55
  • 78
  • 7
    Safari, as of now, still requires `-webkit` flags for flexbox (`display: -webkit-flex;` and `-webkit-align-items: center;` and `-webkit-justify-content: center;`) – Joseph Hansen Jul 23 '15 at 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 – simon Nov 04 '19 at 18:11
305

#centered {
  position: absolute;
  left: 50%;
  margin-left: -100px;
}
<div id="outer" style="width:200px">
  <div id="centered">Foo foo</div>
</div>

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.

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.

Lars Flieger
  • 2,421
  • 1
  • 12
  • 34
Nuno
  • 1,163
  • 1
  • 11
  • 15
  • I don't like this solution because when the inner element is too broad for the screen, you can't scroll over the whole element horizontally. margin: 0 auto works better. – Aloso Dec 30 '15 at 04:02
  • margin-left: auto; margin-right: auto; centres a block level element – bananaforscale Nov 10 '17 at 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). – bananaforscale Nov 10 '17 at 19:16
275

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

And it will stay in the center even when you resize your screen.

iorgv
  • 787
  • 2
  • 11
  • 26
Tom Maton
  • 1,564
  • 3
  • 23
  • 41
  • 18
    +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: http://codepen.io/shshaw/full/gEiDt. One of the more versatile and widely-supported methods of centering elements vertically and/or horizontally. – stvnrynlds Dec 16 '13 at 18:27
  • 9
    You cannot use padding within the div, but if you want to give the illusion use a border of the same color. – Squirrl Jul 09 '14 at 11:45
258

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Danield
  • 121,619
  • 37
  • 226
  • 255
  • what do you mean by "syntax is outdated", is it deprecated? – kongaraju Sep 06 '13 at 10:18
  • 9
    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): http://stackoverflow.com/questions/15662578/flexible-box-model-display-flex-box-flexbox – cimmanon Oct 01 '13 at 20:33
  • Isn't the "justify-content: center;" for the vertical alignment and the "align-items: center;" for the horizontal alignment? – Wouter Vanherck Mar 22 '17 at 12:04
  • 7
    @WouterVanherck it depends on the `flex-direction` value. If it is 'row' (the default) - then `justify-content: center; ` is for the horizontal alignment (like I mentioned in the answer) If it is 'column' - then `justify-content: center;` is for the vertical alignment. – Danield Mar 22 '17 at 12:29
172

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:

#inner {
  display: table;
  margin: 0 auto;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
iorgv
  • 787
  • 2
  • 11
  • 26
Samuel Katz
  • 24,066
  • 8
  • 71
  • 57
157

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.

dippas
  • 58,591
  • 15
  • 114
  • 126
iamnotsam
  • 9,470
  • 7
  • 33
  • 30
  • 3
    This is the only one that works for perfect centering and will remain centered even after the contents in the div are modified. – Phani Rithvij Jul 04 '20 at 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](https://jsfiddle.net/d9xLun6b/2/). – Felypp Oliveira Dec 29 '20 at 12:47
121

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sneakyness
  • 5,305
  • 4
  • 33
  • 39
118

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gizmo
  • 11,819
  • 6
  • 44
  • 61
111

CSS 3's box-align property

#outer {
  width: 100%;
  height: 100%;
  display: box;
  box-orient: horizontal;
  box-pack: center;
  box-align: center;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
iorgv
  • 787
  • 2
  • 11
  • 26
neoneye
  • 50,398
  • 25
  • 166
  • 151
88

The way I usually do it is using absolute position:

#inner {
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  position: absolute;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

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

iorgv
  • 787
  • 2
  • 11
  • 26
william44isme
  • 877
  • 2
  • 13
  • 25
85

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James Moberg
  • 4,360
  • 1
  • 22
  • 21
77

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ch2o
  • 815
  • 2
  • 12
  • 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) – heytools Nov 04 '17 at 02:02
73

Use:

#outerDiv {
  width: 500px;
}

#innerDiv {
  width: 200px;
  margin: 0 auto;
}
<div id="outerDiv">
  <div id="innerDiv">Inner Content</div>
</div>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ankit Jain
  • 1,226
  • 1
  • 10
  • 17
68

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

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.

iorgv
  • 787
  • 2
  • 11
  • 26
Kilian Stinson
  • 2,376
  • 28
  • 33
  • 5
    One may need vendor prefixes as well : `-webkit-transform: translate(-50%,0); -moz-transform: translate(-50%,0); -ms-transform: translate(-50%,0); -khtml-transform: translate(-50%,0); -o-transform: translate(-50%,0);` – Skippy le Grand Gourou Sep 02 '15 at 13:48
57

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;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
iorgv
  • 787
  • 2
  • 11
  • 26
Willem de Wit
  • 8,604
  • 9
  • 57
  • 90
54

I recently found an approach:

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

#inner {
  position: relative;
  left: -50%;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

Both elements must be the same width to function correctly.

iorgv
  • 787
  • 2
  • 11
  • 26
BenjaminRH
  • 11,974
  • 7
  • 49
  • 76
  • Just set this rule for `#inner` only: `#inner { position:relative; left:50%; transform:translateX(-50%); }`. This works for any width. – Jose Rui Santos Nov 24 '15 at 10:30
46

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lalit Kumar Maurya
  • 5,475
  • 2
  • 35
  • 29
42

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!

Community
  • 1
  • 1
John Slegers
  • 45,213
  • 22
  • 199
  • 169
41

This method also works just fine:

#outer { /*div.container*/
  display: flex;
  justify-content: center;
  /* For horizontal alignment */
  align-items: center;
  /* For vertical alignment   */
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

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

iorgv
  • 787
  • 2
  • 11
  • 26
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
40

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 all browsers exept Internet Explorer. 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>

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>

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>
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
37

The easiest way:

#outer {
  width: 100%;
  text-align: center;
}
#inner {
  margin: auto;
  width: 200px;
}
<div id="outer">
  <div id="inner">Blabla</div>
</div>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
joan16v
  • 5,055
  • 4
  • 49
  • 49
36

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;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
iorgv
  • 787
  • 2
  • 11
  • 26
34

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Salman A
  • 262,204
  • 82
  • 430
  • 521
30

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;

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Kenneth P.
  • 1,797
  • 3
  • 21
  • 31
29

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 % );
}
Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
caniz
  • 21
  • 2
  • 2
26

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.

u-ways
  • 6,136
  • 5
  • 31
  • 47
Milan Panigrahi
  • 546
  • 9
  • 11
24

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);
  })
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Miguel Leite
  • 119
  • 1
  • 9
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 */
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pnsadeghy
  • 1,279
  • 1
  • 13
  • 20
  • text-align work for text alignment in its container not for its container to its parent. – Lalit Kumar Maurya Dec 04 '13 at 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 – Pnsadeghy Dec 04 '13 at 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!!!! – Lalit Kumar Maurya Dec 04 '13 at 09:23
  • See this example http://jsfiddle.net/uCdPK/2/ and tell me what do you think about it!!!!! – Lalit Kumar Maurya Dec 04 '13 at 10:03
23

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%)
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shashin Bhayani
  • 1,551
  • 3
  • 16
  • 37
  • Related: *[Will CSS 3 still allow omitting final semicolons?](https://stackoverflow.com/questions/11062615/will-css-3-still-allow-omitting-final-semicolons)* – Peter Mortensen Nov 19 '19 at 12:22
18

Try playing around with

margin: 0 auto;

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

text-align: center;
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;");
});
sarath
  • 343
  • 8
  • 31
18

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Appy Sharma
  • 149
  • 1
  • 6
18

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ChandanK
  • 31
  • 1
  • 5
14

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
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ady Ngom
  • 1,284
  • 2
  • 10
  • 12
12

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aamirha
  • 16
  • 1
  • 2
12

With Grid

A pretty simple and modern way is to use display: grid:

div {
    border: 1px dotted grey;
}

#outer {
    display: grid;
    place-items: center;
    height: 50px; /* not necessary */
}
<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>
        <div id="outer">
            <div>Foo foo</div>
        </div>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
air5
  • 140
  • 2
  • 10
  • 2
    Just learned this today. And people should use this instead of some other hacky ways to solve the centering issue. For people who want to learn more about this, check out https://web.dev/one-line-layouts/ – Joshua Sep 07 '20 at 01:23
10

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.

Ritu
  • 714
  • 6
  • 14
Josh Mc
  • 9,911
  • 8
  • 53
  • 66
9

Use the below CSS content for #inner div:

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

I mostly use this CSS content to center divs.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rajesh
  • 3,743
  • 1
  • 24
  • 31
9

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>
Ritu
  • 714
  • 6
  • 14
ADH - THE TECHIE GUY
  • 4,125
  • 3
  • 31
  • 54
9

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Legends
  • 21,202
  • 16
  • 97
  • 123
8
#inner {
    width: 50%;
    margin: 0 auto;
}
stvnrynlds
  • 2,069
  • 1
  • 14
  • 19
anand jothi
  • 45
  • 1
  • 5
  • Thnx for trying to help the OP :). You shouldn't add answers that are exactly the same as answers already provided. I'm guessing the collision is a mistake but this could have been completely copied and pasted from the accepted answer. – Rapnar Oct 20 '15 at 17:49
8

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>
Saurav Rastogi
  • 9,575
  • 3
  • 29
  • 41
8

To centre an element horizontally you can use these methods:

Method 1: Using margin property

If the element is a block-level element then you can centre the element by using margin property. Set margin-left and margin-right is to auto (Shorthand - margin: 0 auto).

This will align the element to the centre horizontally. If the element is not a block-level element then add display: block property to it.

#outer {
  background-color: silver;
}
#inner {
  width: max-content;
  margin: 0 auto;
  background-color: #f07878;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

Method 2: Using CSS flexbox

Create a flexbox container and use justify-content property and set it to center. This will align all elements horizontally to the centre of the webpage.

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

Method 3: Using position absolute technique

This is a classic method to centre the element. Set postion:relative to the outer element. Set the inner element's position to absolute and left: 50%. This will push the inner element to start from the centre of the outer element. Now use the transform property and set transform: translateX(-50%) this will make the element centre horizontally.

#outer {
  position: relative;
  background-color: silver;
}
#inner {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  background-color: #f07878;
}
<div id="outer">
  <center>
    <div id="inner">Foo foo</div>
  </center>
</div>
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Satish Chandra Gupta
  • 2,970
  • 1
  • 22
  • 22
8

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

Here's a non-exhaustive list of centering approaches, using:

  • margin and auto
  • margin and calc()
  • padding and box-sizing and calc()
  • position: absolute and negative margin-left
  • position: absolute and negative transform: translateX()
  • display: inline-block and text-align: center
  • display: table and display: table-cell
  • display: flex and justify-content: center
  • display: grid and justify-items: center

1. Center a block-level element using auto for horizontal margins

.outer {
  width: 300px;
  height: 180px;
  background-color: rgb(255, 0, 0);
}

.inner {
  width: 150px;
  height: 180px;
  margin: 0 auto;
  background-color: rgb(255, 255, 0);
}
<div class="outer">
  <div class="inner"></div>
</div>

2. Center a block-level element using calc with horizontal margins

.outer {
  width: 300px;
  height: 180px;
  background-color: rgb(255, 0, 0);
}

.inner {
  width: 150px;
  height: 180px;
  margin: 0 calc((300px - 150px) / 2);
  background-color: rgb(255, 255, 0);
}
<div class="outer">
  <div class="inner"></div>
</div>

3. Center a block-level element using calc with horizontal padding + box-sizing

.outer {
  width: 300px;
  height: 180px;
  padding: 0 calc((300px - 150px) / 2);
  background-color: rgb(255, 0, 0);
  box-sizing: border-box;
}

.inner {
  width: 150px;
  height: 180px;
  background-color: rgb(255, 255, 0);
}
<div class="outer">
  <div class="inner"></div>
</div>

4. Center a block-level element using position: absolute with left: 50% and negative margin-left

.outer {
  position: relative;
  width: 300px;
  height: 180px;
  background-color: rgb(255, 0, 0);
}

.inner {
  position: absolute;
  left: 50%;
  width: 150px;
  height: 180px;
  margin-left: -75px;
  background-color: rgb(255, 255, 0);
}
<div class="outer">
  <div class="inner"></div>
</div>

5. Center a block-level element using position: absolute with left: 50% and negative transform: translateX()

.outer {
  position: relative;
  width: 300px;
  height: 180px;
  background-color: rgb(255, 0, 0);
}

.inner {
  position: absolute;
  left: 50%;
  width: 150px;
  height: 180px;
  background-color: rgb(255, 255, 0);
  transform: translateX(-75px);
}
<div class="outer">
  <div class="inner"></div>
</div>

6. Center an element using display: inline-block and text-align: center

.outer {
  position: relative;
  width: 300px;
  height: 180px;
  text-align: center;
  background-color: rgb(255, 0, 0);
}

.inner {
  display: inline-block;
  width: 150px;
  height: 180px;
  background-color: rgb(255, 255, 0);
}
<div class="outer">
  <div class="inner"></div>
</div>

7. Center an element using display: table, padding and box-sizing

.outer {
  display: table;
  width: 300px;
  height: 180px;
  padding: 0 75px;
  background-color: rgb(255, 0, 0);
  box-sizing: border-box;
}

.inner {
  display: table-cell;
  background-color: rgb(255, 255, 0);
}
<div class="outer">
  <div class="inner"></div>
</div>

8. Center an element using display: flex and justify-content: center

.outer {
  display: flex;
  justify-content: center;
  width: 300px;
  height: 180px;
  background-color: rgb(255, 0, 0);
}

.inner {
  flex: 0 0 150px;
  background-color: rgb(255, 255, 0);
}
<div class="outer">
  <div class="inner"></div>
</div>

9. Center an element using display: grid and justify-items: center

.outer {
  display: grid;
  justify-items: center;
  width: 300px;
  height: 180px;
  background-color: rgb(255, 0, 0);
}

.inner {
  width: 150px;
  background-color: rgb(255, 255, 0);
}
<div class="outer">
  <div class="inner"></div>
</div>
Rounin
  • 27,134
  • 9
  • 83
  • 108
7

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sawan mishra
  • 691
  • 1
  • 8
  • 13
6

Make it simple!

#outer {
  display: flex;
  justify-content: center;
}
<div id="outer">  
  <div id="inner">Foo foo</div>
</div>
Hassan Siddiqui
  • 2,799
  • 1
  • 13
  • 22
6

Center an Element Without Need of a Wrapper/Parent with Dynamic Height & Width

No side effect: It will not limit a centered element's width less than the viewport width, when using margins in Flexbox inside a centered element

position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%));

Horizontally + vertically center, if its height is same as the width:

position: fixed;
top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
proseosoc
  • 1,168
  • 14
  • 23
5

One of the easiest ways...

<!DOCTYPE html>
<html>
    <head>
        <style>
            #outer-div {
                width: 100%;
                text-align: center;
                background-color: #000
            }
            #inner-div {
                display: inline-block;
                margin: 0 auto;
                padding: 3px;
                background-color: #888
            }
        </style>
    </head>

    <body>
       <div id ="outer-div" width="100%">
           <div id ="inner-div"> I am a easy horizontally centered div.</div>
       <div>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Asmit
  • 23
  • 1
  • 5
5

If you have a parent of some height say, body{height: 200px} or like the below has parent div#outer with height 200px, then add CSS content as below

HTML:

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

CSS:

#outer{
  display: flex;
  width: 100%;
  height: 200px;
}
#centered {
  margin: auto;
}

Then child content, say div#centered content, will be vertically or horizontally middle, without using any position CSS. To remove vertically middle behavior then just modify to below CSS code:

#centered {
  margin: 0px auto;
}

or

#outer{
  display: flex;
  width: 100%;
  height: 200px;
}
#centered {
  margin: auto;
}

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

Demo: https://jsfiddle.net/jinny/p3x5jb81/5/

To add only a border to show the inner div is not 100% by default:

#outer{
  display: flex;
  width: 100%;
  height: 200px;
  border: 1px solid #000000;
}
#centered {
  margin: auto;
  border: 1px solid #000000;
}
<div id="outer">
  <div id="centered">Foo foo</div>
</div>

DEMO: http://jsfiddle.net/jinny/p3x5jb81/9

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shoma
  • 479
  • 3
  • 9
  • if you look into https://jsfiddle.net/jinny/p3x5jb81/9/ , i just added border to show that in my case centered div is not 100%, it takes size/length of the text content. If centered text has content length bigger than the outer div than I agree we need to give inner div a width. But my solution support the given sample case. – Shoma Apr 28 '20 at 03:14
5

With Sass (SCSS syntax) you can do this with a mixin:

With translate

// Center horizontal mixin
@mixin center-horizontally {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

In an HTML tag:

<div class="center-horizontally">
    I'm centered!
</div>

Remember to add position: relative; to the parent HTML element.


With Flexbox

Using flex, you can do this:

@mixin center-horizontally {
  display: flex;
  justify-content: center;
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

In an HTML tag:

<div class="center-horizontally">
    <div>I'm centered!</div>
</div>

Try this CodePen!

Alessandro_Russo
  • 1,799
  • 21
  • 34
5

To align a div within a div in middle -

.outer{
  width: 300px; /* For example */
  height: 300px; /* For example */
  background: red;
}
.inner{
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 200px;
  height: 200px;
  background: yellow;
}
<body>
  <div class='outer'>
    <div class='inner'></div>
  </div>
</body>

This will align the internal div in the middle, both vertically and horizontally.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Utkarsh Tyagi
  • 1,379
  • 1
  • 7
  • 12
5

Just do this:

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

CSS

#outer{
  display: grid;
  place-items: center;
}

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdullah Ch
  • 1,678
  • 1
  • 13
  • 31
5

This can be done by using lots of methods. Many guys'/gals' given answers are correct and working properly. I'll give one more different pattern.

In the HTML file

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

In the CSS file

#outer{
  width: 100%;
}

#inner{
  margin: auto;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tharindu Lakshan
  • 3,995
  • 6
  • 24
  • 44
4

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
4

Try out this below CSS code:

<style>
    #outer {
        display: inline-block;
        width: 100%;
        height: 100%;
        text-align: center;
        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;
    }
</style>

Apply above CSS via below HTML code, to center horizontally and to center vertically (aka: align vertically in middle):

<div id="outer">
    <div id="inner">
    ...These <div>ITEMS</div> <img src="URL"/> are in center...
    </div>
</div>

After applying CSS & using above HTML, that section in webpage would look like this:

BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃V..Middle & H..Center        ┣━1
┃                             ┣━2
┃                             ┣━3
┗┳━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━┳┛
 1      2      3      4      5

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                             ┣━1
┃    V..Middle & H..Center    ┣━2
┃                             ┣━3
┗┳━━━━━━┳━━━━━━┳━━━━━━┳━━━━━━┳┛
 1      2      3      4      5

To center "inner" elements horizontally inside the "outer" wrapper, the "inner" elements (of type DIV, IMG, etc) need to have "inline" CSS properties, such as these: display:inline or display:inline-block, etc, THEN "outer" CSS property text-align:center can work on "inner" elements.

So near to minimum CSS code are these:

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

    #outer > .inner2 {
        display: inline-block;
    }
</style>

Apply above CSS via below HTML code, to center (horizontally):

<div id="outer">
    <img class="inner2" src="URL-1"> <img class="inner2" src="URL-2">
</div>

After applying CSS & using above HTML, that line in webpage would look like this:

BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃┍━━━━━━━━━━┑                     ┃
┃│ img URL1 │                     ┃
┃┕━━━━━━━━━━┙                     ┃
┃┍━━━━━━━━━━┑                     ┃
┃│ img URL2 │                     ┃
┃┕━━━━━━━━━━┙                     ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃    ┍━━━━━━━━━━┑ ┍━━━━━━━━━━┑    ┣━1
┃    │ img URL1 │ │ img URL2 │    ┣━2
┃    ┕━━━━━━━━━━┙ ┕━━━━━━━━━━┙    ┣━3
┗┳━━━━━━━┳━━━━━━━┳━━━━━━━┳━━━━━━━┳┛
 1       2       3       4       5

If you want to avoid specifying class="inner2" attribute everytime for each "inner" elements, then use such CSS in early:
<style>
    #outer {
        width: 100%;
        text-align: center;
    }

    #outer > img, #outer > div {
        display: inline-block;
    }
</style>

So above CSS can be applied like below, to center items (horizontally) inside the "outer" wrapper:

<div id="outer">
    <img src="URL-1"> Text1 <img src="URL-2"> Text2
</div>

After applying CSS & using above HTML, that line in webpage would look like this:

BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃┍━━━━━━━━┑                ┃
┃│img URL1│                ┃
┃┕━━━━━━━━┙                ┃
┃Text1                     ┃
┃┍━━━━━━━━┑                ┃
┃│img URL2│                ┃
┃┕━━━━━━━━┙                ┃
┃Text2                     ┃
┗━━━━━━━━━━━━━━━━━━━━━━━━━━┛

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃   ┍━━━━━━━━━┑     ┍━━━━━━━━┑        ┣━1
┃   │img URL1 │     │img URL2│        ┣━2
┃   ┕━━━━━━━━━┙Text1┕━━━━━━━━┙Text2   ┣━3
┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛
 1        2        3        4        5

The "id" attribute's unique name/value should be used only once for only one HTML element in one webpage, So CSS properties of same "id" name cannot be repeatedly used on multiple HTML elements, (some web-browser incorrectly allows to use same id on multiple elements).
So when you need many lines in same webpage, that need to show internal elements/items in center (horizontally) in that line, then you may use such CSS "class" (aka: CSS group, CSS repeater):
<style>
    .outer2 {
        width: 100%;
        text-align: center;
    }

    .outer2 > div, .outer2 > div > img {
        display: inline-block;
    }
</style>

So above CSS can be applied like below, to center items (horizontally) inside the "outer2" wrapper:

<div class="outer2">
    <div>
        Line1: <img src="URL-1"> Text1 <img src="URL-2">
    </div>
</div>
...
<div class="outer2">
    <div>
        Line2: <img src="URL-3"> Text2 <img src="URL-4">
    </div>
</div>

After applying CSS & using above HTML, those lines in webpage would look like this:

BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━┓
┃Line1:                ┃
┃┍━━━━━━━━┑            ┃
┃│img URL1│            ┃
┃┕━━━━━━━━┙            ┃
┃Text1                 ┃
┃┍━━━━━━━━┑            ┃
┃│img URL2│            ┃
┃┕━━━━━━━━┙            ┃
┗━━━━━━━━━━━━━━━━━━━━━━┛
........................
┏━━━━━━━━━━━━━━━━━━━━━━┓
┃Line2:                ┃
┃┍━━━━━━━━┑            ┃
┃│img URL3│            ┃
┃┕━━━━━━━━┙            ┃
┃Text2                 ┃
┃┍━━━━━━━━┑            ┃
┃│img URL4│            ┃
┃┕━━━━━━━━┙            ┃
┗━━━━━━━━━━━━━━━━━━━━━━┛

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃         ┍━━━━━━━━┑     ┍━━━━━━━━┑   ┣━1
┃         │img URL1│     │img URL2│   ┣━2
┃   Line1:┕━━━━━━━━┙Text1┕━━━━━━━━┙   ┣━3
┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛
 1        2        3        4        5
.......................................
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃         ┍━━━━━━━━┑     ┍━━━━━━━━┑   ┣━1
┃         │img URL3│     │img URL4│   ┣━2
┃   Line2:┕━━━━━━━━┙Text2┕━━━━━━━━┙   ┣━3
┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛
 1        2        3        4        5

To vertically align in middle, we would need to use below CSS code:
<style>
    .outer2 {
        width: 100%;
        text-align: center;
        vertical-align: middle;
    }

    .outer2 > div, .outer2 > div > img {
        display: inline-block;
        vertical-align: middle;
    }
</style>

So above CSS can be applied like below, to center items horizontally and to vertically align in middle of the "outer2" wrapper:

<div class="outer2">
    <div>
        Line1: <img src="URL-1"> Text1 <img src="URL-2">
    </div>
</div>
...
<div class="outer2">
    <div>
        Line2: <img src="URL-3"> Text2 <img src="URL-4">
    </div>
</div>

After applying CSS & using above HTML, those lines in webpage would look like this:

BEFORE applying code:
┏━━━━━━━━━━━━━━━━━━━━━━┓
┃Line1:                ┃
┃┍━━━━━━━━┑            ┃
┃│img URL1│            ┃
┃┕━━━━━━━━┙            ┃
┃Text1                 ┃
┃┍━━━━━━━━┑            ┃
┃│img URL2│            ┃
┃┕━━━━━━━━┙            ┃
┗━━━━━━━━━━━━━━━━━━━━━━┛
........................
┏━━━━━━━━━━━━━━━━━━━━━━┓
┃Line2:                ┃
┃┍━━━━━━━━┑            ┃
┃│img URL3│            ┃
┃┕━━━━━━━━┙            ┃
┃Text2                 ┃
┃┍━━━━━━━━┑            ┃
┃│img URL4│            ┃
┃┕━━━━━━━━┙            ┃
┗━━━━━━━━━━━━━━━━━━━━━━┛

AFTER:
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃         ┍━━━━━━━━┑     ┍━━━━━━━━┑   ┣━1
┃   Line1:│img URL1│Text1│img URL2│   ┣━2
┃         ┕━━━━━━━━┙     ┕━━━━━━━━┙   ┣━3
┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛
 1        2        3        4        5
.......................................
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃         ┍━━━━━━━━┑     ┍━━━━━━━━┑   ┣━1
┃   Line2:│img URL3│Text2│img URL4│   ┣━2
┃         ┕━━━━━━━━┙     ┕━━━━━━━━┙   ┣━3
┗┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳━━━━━━━━┳┛
 1        2        3        4        5
atErik
  • 923
  • 2
  • 13
  • 24
Ajay Gupta
  • 2,867
  • 23
  • 28
4

You can use CSS 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/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cyan Baltazar
  • 3,462
  • 1
  • 17
  • 11
4

The 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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Faizal Munna
  • 515
  • 5
  • 21
4

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%)
}
Agu Dondo
  • 12,638
  • 7
  • 57
  • 68
4

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 two important things you shouldn't forget in your CSS when you try to center this way: margin: 0 auto;. That makes it the div center as wanted. Plus don't forget width of the child, otherwise it won't get centered as expected!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alireza
  • 100,211
  • 27
  • 269
  • 172
4

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>
antelove
  • 3,216
  • 26
  • 20
  • Thank you for your answer! If you think that your answer contributes something valuable to the question, be sure to further explain your code and what it does and why it works, thanks! – Ian H. Sep 23 '17 at 17:29
  • 1
    this worked for me. most of the time display block then margin auto for inner div doesnt work but with the display flex in outer div worked great. thanks alot. I havent tried the display flex before. – livefreeor Oct 12 '17 at 01:13
  • me too. using display table also great. my another answer. https://stackoverflow.com/questions/5703552/css-center-text-horizontally-and-vertically-inside-a-div-block/46452713#46452713 – antelove Oct 12 '17 at 09:30
4

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Руслан
  • 675
  • 7
  • 8
4

You can use 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sed
  • 5,431
  • 2
  • 24
  • 23
4

Here is another way to center horizontally using Flexbox and without specifying any width to the 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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
4

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

Jaison James
  • 4,414
  • 4
  • 42
  • 54
4

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>
Mark Salvania
  • 486
  • 3
  • 17
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Morteza Sadri
  • 695
  • 9
  • 18
4

This worked for me:

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

In this code, you determine the width of the element.

Raghul SK
  • 1,256
  • 5
  • 22
  • 30
4

.outer
{
  background-color: rgb(230,230,255);
  width: 100%;
  height: 50px;
}
.inner
{
  background-color: rgb(200,200,255);
  width: 50%;
  height: 50px;
  margin: 0 auto;
}
<div class="outer">
  <div class="inner">
    margin 0 auto
  </div>
</div>
pavelbere
  • 964
  • 10
  • 21
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jual ahmed
  • 439
  • 5
  • 14
3

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>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Yahya Essam
  • 1,832
  • 2
  • 23
  • 44
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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Heitor
  • 683
  • 2
  • 12
  • 26
  • 2
    The `
    ` tag is deprecated since HTML4, like [Idra explained in comments](https://stackoverflow.com/questions/114543/how-to-horizontally-center-a-div-in-another-div/45251566#comment32214515_20339458)
    – Garric Jul 25 '17 at 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
    despite it keeps working perfectly fine in some cases. The
    tag was deprecated but nothing as simple and effective as it came to replace it decently in all cases.
    – Heitor Jul 26 '17 at 15:17
3

Use this code:

#inner {
   width: 50%;
   margin: 0 auto;
   text-align: center;
}
<div id="outer">
    <div id="inner">Foo foo</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Husain Ahmed
  • 815
  • 7
  • 27
3
div{
    width: 100px;
    height: 100px;
    margin: 0 auto;
}

For the normal thing if you are using div in a static way.

If you want a div to be 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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

You can add another div which has the same size of #inner and move it to the left by -50% (half of the width of #inner) and #inner by 50%.

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

#inner > div {
    position: relative;
    left: -50%;
}
<div id="outer">
  <div id="inner"><div>Foo foo</div></div>
</div>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SB3NDER
  • 63
  • 5
3

In the previous examples they used margin: 0 auto, display:table and other answers used "with transform and translate".

And what about just with a tag? Everyone knows there is a <center> tag which is just not supported by HTML5. But it works in HTML5. For instance, in my old projects.

And it is working, but now not only MDN Web Docs, but other websites are advising not to use it any more. Here in Can I use you can see notes from MDN Web Docs. But whatever, there is such a way. This is just to know. Always being noticed about something is so useful.

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • `
    ` is only a predefined tag, not adjustable, not flexible as in CSS. It still works but those are one of the last living remnants just like and . Deprecated doesn't mean that it will no more work in future... it also means that new techonolgies, be it via node react using JSX or other complex MVCs that generate virtual DOMs might be not fully capable to work with. That they still work in HTML5 despite not supported means that w3c no longer maintains it. Also SEO: Websites with deprecated HTML may signalize search engines with outdated code which could harm your ranking.
    – Thielicious Jun 02 '20 at 23:53
3

Try this:

<div style="position: absolute;left: 50%;top: 50%;-webkit-transform: translate(-50%, -50%);transform: translate(-50%, -50%);"><div>Example</div></div>
mdmundo
  • 1,988
  • 2
  • 23
  • 37
3

In my case I needed to center(on screen) a dropdown menu(using flexbox for it's items) below a button that could have various locations vertically. None of the suggestions worked until I changed position from absolute to fixed, like this:

#outer {
      margin: auto;
      left: 0;
      right: 0;
      position: fixed;
}
#inner {
      text-align: center;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

The above codes makes the dropdown to always center on the screen for devices of all sizes, no matter where the dropdown button is located vertically.

samnoon
  • 1,340
  • 2
  • 13
  • 23
John T
  • 814
  • 10
  • 17
3

There are several ways to achieve it: using "flex", "positioning", "margin" and others. Assuming #outer and #inner divs given in the question:

I would recommend using "flex"

#outer {
   display: flex;
   justify-content: center;
   align-items: center;  /* if you also need vertical center */
}

Horizontal align using positioning

#outer {
  position: relative;
}
#inner {
  position: absolute;
  left: 50%;
  translate: transformX(-50%)
}

Horizontal and vertical-align using positioning

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

Horizontal align using margin

#inner {
 width: fit-content;
 margin: 0 auto;
}
Ismoil Shokirov
  • 2,213
  • 2
  • 16
  • 32
2
#outer {
   position: relative;
}

#inner {
   width: 100px;
   height: 40px;
   position: absolute;
   top: 50%;
   margin-top: -20px; /* half of your height */
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Majid Sadr
  • 911
  • 7
  • 18
2

Depending on your circumstances, the simplest solution could be:

margin: 0 auto; 
float: none;
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Justin Munce
  • 187
  • 1
  • 9
2

Yes, this is short and clean code for horizontal alignment.

.classname {
   display: box;
   margin: 0 auto;
   width: 500px /* Width set as per your requirement. */;
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Banti Mathur
  • 41
  • 1
  • 5
2

Just decide what width you want to give to the inner <div> and use the following CSS:

.inner {
   width: 500px; /* Assumed width */
   margin: 0 auto;
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Gaurav Aggarwal
  • 9,809
  • 6
  • 36
  • 74
2

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

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;
}
Mardok
  • 1,360
  • 10
  • 14
2

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mr.Pandya
  • 1,899
  • 1
  • 13
  • 24
2

CSS

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

HTML

<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>
Abhishek Pandey
  • 13,302
  • 8
  • 38
  • 68
Abdul Ghaffar
  • 228
  • 3
  • 14
2

Use the below code.

#outer {
   text-align: center;
}

#inner {
   display: inline-block;
}
<div id="outer">
    <div id="inner">Foo foo</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Faizal
  • 250
  • 1
  • 8
2

You can add this code:

#inner {
  width: 90%;
  margin: 0 auto;
  text-align:center;
}
<div id="outer">  
  <div id="inner">Foo foo</div>
</div>
Rafiqul Islam
  • 931
  • 11
  • 14
2

We could use the next CSS class which allows to center vertically and horizontally any element against its parent:

.centerElement {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Kenzo_Gilead
  • 2,187
  • 9
  • 35
  • 60
2

Use:

<style>
  #outer{
    text-align: center;
    width: 100%;
  }
  #inner{
    text-align: center;
  }
</style>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SUNIL KUMAR E.U
  • 85
  • 1
  • 11
2

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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shivam Chhetri
  • 677
  • 11
  • 16
2

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>
drewkiimon
  • 591
  • 1
  • 9
  • 16
2

CSS justify-content property

It aligns the Flexbox items at the center of the container:

#outer {
    display: flex;
    justify-content: center;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Priya jain
  • 1,127
  • 2
  • 10
  • 22
2

#outer {
   display: grid;
   justify-content: center;
}
<div id="outer">
    <div id="inner">hello</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
sabban
  • 131
  • 5
2

I've seen lots and lots of answers and they are all outdated. Google already implemented a solution for this common problem, which centers the object literally in the middle no matter what happens, and YES it's responsive. So never do transform() or position manually ever again.

.HTML

...
<div class="parent">
   <form> ... </form>
   <div> ... </div>
</div>

.CSS

.parent {
   display: grid;
   place-items: center;
}
Egon Stetmann.
  • 461
  • 6
  • 14
2

Recap 2022

This is a very old question so I'm just trying to report the situation today:

  • CSS grid and flexbox are the best options you have for centering, horizontal or vertical;
  • margin:auto method works well if the inner content is not a box (inline-block is okay);
  • margin 50% with transform:translateX(-50%) is brute force but works allright;
  • same thing with absolute positions and translateX/Y is good for horizontal and vertical centering too, many dialogs use that, stretching height to 100vh;
  • the good old text-align:center with inline-block still works
  • the ancient demon called "center tag" still works, actually it's the easiest way for horizontal centering. Deprecated, feared & hated by many but still;
  • tables (td tags, actually) can center beautifully, horizontal and vertical, but they're also called old hat;
  • these last 2 will work in email templates too (they're HTML4) if you're unlucky enough to work on one.

That's what it looks like in 2022, and I hope we'll never need more than grids and flexboxes. Those guys are the answer to all our prayers in 1999.

dkellner
  • 8,726
  • 2
  • 49
  • 47
1

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; }
uSeRnAmEhAhAhAhAhA
  • 2,527
  • 6
  • 39
  • 64
1

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hossein ketabi
  • 480
  • 7
  • 19
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
1

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nyn05
  • 540
  • 5
  • 17
1

#outer {
   width: 500px;
   background-color: #000;
   height: 500px;
}

#inner {
   background-color: #333;
   margin: 0 auto;
   width: 50%;
   height: 250px;
}
<div id="outer">
    <div id="inner"></div>
</div>

JSFiddle

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
1

Add text-align:center; to parent <div>:

#outer {
   text-align: center;
}

JSFiddle

Or

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

JSFiddle

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Friend
  • 506
  • 4
  • 10
1

Try margin: 0px auto;.

#inner {
   display: block;
   margin: 0px auto;
   width: 100px;
}
<div id="outer" style="width: 100%;">
    <div id="inner">Foo foo</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Sankar
  • 6,908
  • 2
  • 30
  • 53
1

You can do it in different ways. See the below examples.

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

#inner {
   display: inline-block;
}
  1. Second method
#outer {
   position: relative;
   overflow: hidden;
}
.centered {
   position: absolute;
   left: 50%;
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Gaurang Sondagar
  • 814
  • 1
  • 9
  • 23
1

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

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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anu
  • 121
  • 2
  • 9
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation would greatly improve its long-term value](//meta.stackexchange.com/q/114762/350567) by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you've made. – iBug Jan 25 '18 at 07:35
1

#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>
Galarist
  • 27
  • 1
  • 7
1

My updated and preferred solution is this:

#inner {
  width: 100%;
  max-width: 65px; /*width of the content*/
  margin: 0 auto;/*this will make put the div in the center*/
  text-align: center;/*this will center the text inside the div*/
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>

With flexbox:

#outer {
  display: flex;
  justify-content: center;
  align-items: center;
}
<div id="outer">
  <div id="inner">Foo foo</div>
</div>
iorgv
  • 787
  • 2
  • 11
  • 26
1
#inner {
   width: 50%;
   margin: 0 auto;
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Javed Khan
  • 395
  • 5
  • 9
1

You can horizontally center a <div> within another <div> by using text-align Property in CSS.

text-align: center is used to center the text of the outer div horizontally.

text-align: right is used to align the text to the right.

text-align: left is used to align the text to the left.

text-align: justify is used to stretch the lines so that each line has equal width.

div.a {
  text-align: center;
}

div.b {
  text-align: left;
}

div.c {
  text-align: right;
} 

div.d {
  text-align: justify;
} 
<h1>The text-align Property</h1>

<div class="a">
<h2>text-align: center:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>

<div class="b">
<h2>text-align: left:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>

<div class="c">
<h2>text-align: right:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>

<div class="d">
<h2>text-align: justify:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut.</p>
</div>
Mubeen Ahmad
  • 428
  • 3
  • 11
1

Updated 2022 Centering Element Horizontally

1. Horizontally centering using flexbox

To horizontally center a elements like (div) need to add display:flex and justify-content:center to the element css class.

<div class="center">
   <h1>I'm Horizontally center</h1>
</div>
.center{
   display:flex;
   justify-content:center;
}

2. Horizontally centering using margins

Below example shows how to horizontally center elements using margins and width.

.center{
    width:50%;
    margin:0 auto;
}

In the above code, have added width:50% and margin:0 auto so that the element equally splits the available space between the left and right margins.

3. Horizontally centering using transform

Below example shows how to horizontally center elements using position and transform properties.

.center{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
  • Firstly added position:absolute, so that element comes out from the normal document flow.
  • second we added left:50%, so that element moves forward 50% towards x-axis.
  • Third, we added transform:translateX(-50%), so that element comes backward 50% and align it to center.
pr96
  • 994
  • 5
  • 17
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bonyem
  • 1,148
  • 11
  • 20
0

Flexbox Center Horizontally and Vertically Center Align an Element

.wrapper {border: 1px solid #678596; max-width: 350px; margin: 30px auto;} 
      
.parentClass { display: flex; justify-content: center; align-items: center; height: 300px;}
      
.parentClass div {margin: 5px; background: #678596; width: 50px; line-height: 50px; text-align: center; font-size: 30px; color: #fff;}
<h1>Flexbox Center Horizontally and Vertically Center Align an Element</h1>
<h2>justify-content: center; align-items: center;</h2>

<div class="wrapper">

<div class="parentClass">
  <div>c</div>
</div>

</div>
Jone
  • 150
  • 7
0

Try the below example but the container should have a width, for example 100%.

button {
   margin: 0 auto;
   width: fit-content;
   display: block;
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Vasyl Gutnyk
  • 4,813
  • 2
  • 34
  • 37
0

#outer {
   display: grid;
   place-items: center;
}
<div id="outer">
    <div id="inner">Foo foo</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Krutik Raut
  • 139
  • 7
0

I'd simply suggest using justify-content: center; when the container is displayed as flex. and text-align: center; when it is about a text element.

check the code below and modify as per the requirements.

#content_block {
  border: 1px solid black;
  padding: 10px;
  width: 50%;
  text-align: center;
}

#container {
  border: 1px solid red;
  width:100%;
  padding: 20px;
  display: flex;
  justify-content: center;
}
<div id="container">
  <div id="content_block">Foo foo check</div>
</div>
Anil Parshi
  • 875
  • 5
  • 21
0
#outer {
   display: flex;
   width: 100%;
   height: 200px;
   justify-content: center;
   align-items: center;
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
0

* {
   margin: 0;
   padding: 0;
}

#outer {
   background: red;
   width: 100%;
   height: 100vh;
   display: flex;
   /*center For  vertically*/
   justify-content: center;
   flex-direction: column;
   /*center for horizontally*/
   align-items: center;
}

#inner {
   width: 80%;
   height: 40px;
   background: grey;
   margin-top: 5px;
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>horizontally center an element</title>
    </head>

    <body>
        <div id="outer">
            <div id="inner">1</div>
            <div id="inner" style="background: green;">2</div>
            <div id="inner" style="background: yellow;">3</div>
        </div>
    </body>
</html>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Vishal Kardam
  • 24
  • 1
  • 9
0

.res-banner {
    width: 309px;
    margin: auto;
    height: 309px;
}
<div class="container">
    <div class="res-banner">
        <img class="imgmelk" src="~/File/opt_img.jpg" />
    </div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
mirazimi
  • 814
  • 10
  • 11
0

#outer {
    display: flex;
    align-items: center;
}
<div id="outer">
    <div id="inner">Foo foo</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
0

An element can be centered horizontally easing using the CSS Flexbox property.

#outer {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}
<div id="outer">
    <div id="inner">Foo foo</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
0

If you want to center an element horizontally you can do like this:

1. Method one: Using flexbox.

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

If you want to align vertically center as well, just add align-items: center;. For this to work you need to give a certain height to the #outer.

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

2. Method 2: Using margin. For this method to work you need to give your #inner a certain width.

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

3. Method 3: Using (margin + translate). For this to work you need to give certain width to #inner.

#inner {
  width: 50%;
  margin-left: 50%;
  transform: translateX(-50%);
}
-1

For a horizontally centered <div>:

#outer {
    width: 100%;
    text-align: center;
}
#inner {
    display: inline-block;
}
<div id="outer">
    <div id="inner">Foo foo</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Riddhi Busa
  • 116
  • 1
  • 11
-1

I think this will be a solution:

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

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

Both elements must be the same width to function separately.

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
-2

You can use this link.

.outer {
   display: table;
   width: 100%;
   height: 100%;
}
.inner {
   vertical-align: middle;
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Sibaram Sahu
  • 990
  • 2
  • 13
  • 21
-2

You can use <center> tag for convenience.

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

Note: <center> is deprecated and shouldn't be used anymore.

Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Harvir
  • 131
  • 7
  • 1
    A one line answer is not high quality. I'm not even sure that a center tag would work without limiting the width of the inner div. Can you give a working example? – Stephen Ostermiller Nov 25 '22 at 02:51
  • all u have to do is use a center tag literally, there is nothing sophisticated about this – Harvir Nov 25 '22 at 06:48
  • 1
    The center element is deprecated https://developer.mozilla.org/en-US/docs/Web/HTML/Element/center – Mohamed Dec 25 '22 at 21:31
-3

Try this:

.outer {
   text-align: center;
}
.inner {
   width: 500px;
   margin: 0 auto;
   background: brown;
   color: red;
}
<div class="outer">
    <div class="inner">This DIV is centered</div>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
-5

You can horizontally align any element using:

<div align=center>
    (code goes here)
</div>

Or:

<!-- css here -->
    .center-me {
        margin: 0 auto;
    }

<!-- html here -->
    <div class="center-me">
        (code goes here)
    </div>
legend
  • 41
  • 5
  • `align` is deprecated on `div`: https://developer.mozilla.org/en-US/docs/Web/API/HTMLDivElement, and the second answer has already been given on several others. – General Grievance Jul 03 '23 at 12:57