0

I want to place a <div> into another and want to center it. My way is this:

<div id="redthing">
<div id="whitebox" >
</div>
</div>

The .css - code is the following:

#redthing {
margin-top: 2px;
background-color: #f00d28;
height: 250px;
}

#whitebox {
 margin: 0 auto;
 margin-top: 10px;
 padding-top: 20px;
 height: 10px;
 width: 400px;
 background-color: white;
 border:5px solid #000;
}

Like you can see, padding and margin does not work to center it in the middle of the page(that means that there is the same place between the whitebox and the top and the bottom of the redbox. Please help

user896692
  • 2,351
  • 7
  • 36
  • 57
  • See http://stackoverflow.com/questions/396145/whats-the-best-way-of-centering-a-div-vertically-with-css – Bali Balo Jul 22 '12 at 17:10

1 Answers1

4

Well, let's take a look at what you have. Every line in this drawing represents 10px in height:

┏━━━━━━━━━━━━━━━━━━━━━┓
┃10px margin top        ┃
┃┌─────────────────────┐┃
┃│20px padding top     │┃
┃│padding continues    │┃
┃│10px height          │┃
┃└─────────────────────┘┃
┃                       ┃
┊  lots of empty space  ┊
┃                       ┃
┗━━━━━━━━━━━━━━━━━━━━━┛

Explain how that's supposed to work?

You either need to make sure your padding and margin add up to the correct amount, or use this:

/* add this to the container */
position: relative;

/* add this to the inner box */
position: absolute;
top: 50%;
margin-top: -Xpx;
/* where X is half the offsetHeight of the box - ie. (height+padding+border)/2 */
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592