How can I center a div within another div? [duplicate]

Solution 1:

You need to set the width of the container (auto won't work):

#container {
    width: 640px; /* Can be in percentage also. */
    height: auto;
    margin: 0 auto;
    padding: 10px;
    position: relative;
}

The CSS reference by MDN explains it all.

Check out these links:

  • auto - CSS reference | MDN
  • margin - CSS reference | MDN
  • What is the meaning of auto value in a CSS property - Stack Overflow

In action at jsFiddle.

Solution 2:

Technically, your inner DIV (#container) is centered horizontally. The reason you can't tell is because with the CSS width: auto property the inner DIV is expanding to the same width as its parent.

See this fiddle: http://jsfiddle.net/UZ4AE/

#container {
    width: 50px;
    height: auto;
    margin: 0 auto;
    padding: 10px;
    position: relative;
    background-color: red;
}

In this example, I simply set the width of #container to 50px and set the background to red so that you can see that it is centered.

I think the real question is "How do I center elements horizontally with CSS?" and the answer is (drum roll please): it depends!

I won't do a full rehash of the myriad ways to center things with CSS when W3Schools does it so nicely here: http://www.w3schools.com/css/css_align.asp but the basic idea is that for block level elements you simply specify the desired width and set the left and right margins to auto.

.center {
    margin-left: auto;
    margin-right: auto;
    width: 50px;
}

Please note: This answer only applies to block level elements! To position an inline element, you will need to use the text-align: center property on the first block parent.

Solution 3:

Another interesting way: fiddle

CSS

.container {
   background: yellow;
   width: 100%;
   display: flex;
   flex-direction: row;
   flex-wrap: wrap;
   justify-content: center;
   align-items: center;
}

.centered-div {
   width: 80%;
   height: 190px;
   margin: 10px;
   padding: 5px;
   background: blue;
   color: white;
}

HTML

    <div class="container">
        <div class="centered-div">
            <b>Enjoy</b>
        </div>
    </div>