Cómo centrar horizontalmente un <div>

Sep 22 2008

¿Cómo puedo centrar horizontalmente un <div>dentro de otro <div>usando CSS?

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

Respuestas

4930 AhmerMH Sep 22 2008 at 19:29

Puede aplicar este CSS al interior <div>:

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

Por supuesto, usted no tiene que establecer el widtha 50%. Cualquier ancho menor que el que contiene <div>funcionará. El margin: 0 autoes lo que hace el centrado real.

Si está apuntando a Internet Explorer 8 (y posterior), podría ser mejor tener esto en su lugar:

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

Hará que el elemento interior se centre horizontalmente y funcionará sin establecer una especificación width.

Ejemplo de trabajo aquí:

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


EDITAR

Con flexboxél es muy fácil diseñar el div centrado horizontal y verticalmente.

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

Para alinear el div centrado verticalmente, use la propiedad align-items: center.

1288 Alfred Jan 21 2011 at 05:55

Si no desea establecer un ancho fijo en el interior div, puede hacer algo como esto:

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

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

Eso convierte el interior diven un elemento en línea con el que se puede centrar text-align.

401 KongaRaju Aug 30 2012 at 19:05

Los mejores enfoques son con CSS 3 .

Modelo de caja:

#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

  • Link 2

  • Link 3

  • Link 4

And this explains why the box model is the best approach:

  • Why is the W3C box model considered better?
265 nuno_cruz Dec 02 2011 at 02:52

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.

240 TomMaton Sep 11 2013 at 18:32

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.

226 Danield Apr 22 2013 at 17:32

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.

147 SalmanvonAbbas May 13 2012 at 06:45

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;
}
112 iamnotsam May 18 2014 at 01:38

Centering a div of unknown height and width

Horizontally and vertically. It works with reasonably modern browsers (Firefox, Safari/WebKit, Chrome, Internet Explorer 10, Opera, etc.)

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

Tinker with it further on Codepen or on JSBin.

98 Sneakyness Jul 25 2009 at 05:00

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.

97 gizmo Sep 22 2008 at 19:30

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

95 neoneye Mar 11 2012 at 20:37

CSS 3's box-align property

#outer {
    width: 100%;
    height: 100%;
    display: box;
    box-orient: horizontal;
    box-pack: center;
    box-align: center;
}
71 JamesMoberg Jun 24 2011 at 04:42

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>

68 william44isme Apr 07 2013 at 15:22

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.

62 ch2o May 31 2012 at 22:32

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.

58 AnkitJain Jul 19 2013 at 17:21

Use:

#outerDiv {
  width: 500px;
}

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

55 KilianStinson Mar 12 2015 at 21:01

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.

50 WillemdeWit Oct 25 2013 at 18:53

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;
}
45 BenjaminRH May 27 2013 at 23:12

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.

39 LalitKumar Dec 04 2013 at 14:30

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.

34 JohnSlegers Feb 19 2016 at 23:57

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!

32 joan16v Aug 22 2014 at 19:10

The easiest way:

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

32 SalmanA Jan 18 2014 at 01:18

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>

28 KennethPalaganas Oct 14 2013 at 19:09

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;

28 PaoloForgia Jun 09 2017 at 15:34

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:

  • display: block
  • display: inline
  • display: inline-block

#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

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>

26 caniz Jan 28 2014 at 16:55

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 % );
}
25 SandeshDamkondwar Apr 04 2017 at 03:12

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;
}
25 MilanPanigrahi Jun 10 2018 at 22:53

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.

24 BillalBegueradj Sep 23 2016 at 13:49

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 MiguelLeite Feb 11 2014 at 22:51

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);
  })
});
21 Pnsadeghy Nov 17 2013 at 02:56

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