1

I'm learning how to use the position relative/absolute.

However, I've come a little stuck.

I'm trying to horizontally center a div within a div but when I add margin: 0 auto; it does nothing.

I've made a Fiddle.

Or here's the code:

<!DOCTYPE HTML>
<html lang="en-UK">
    <head>
        <link href="DivTest.css" rel ="stylesheet" type="text/css">
        <title></title>
    </head>
    <body>
    <div id="header"></div>
    <div id="outer">
        <div id="inner"></div>
    </div>
    </body>
</html>

CSS:

body, html {
     margin: 0;
     width: 100%;
}

#header{
     position: relative;
     width: 100%;
     height: 200px;
     background-color: lightgreen;
     margin: 0 0 20px 0;
}

#outer{
     position: relative;
     width: 800px;
     height: 500px;
     background-color: red;
     margin: 0 auto;

}

#inner{
     position: absolute;
     width: 200px;
     height: 250px;
     background-color: lightblue;
     margin: 0 auto;
}

Any help would be appreciated.

username
  • 4,258
  • 1
  • 16
  • 26
Michael
  • 515
  • 2
  • 13
  • 25

1 Answers1

3

Just remove the position:absolute; property for #inner

Fiddle: http://jsfiddle.net/Q8NVH/7/

naveen
  • 53,448
  • 46
  • 161
  • 251
  • @JaredFarrish: actually i also created an updated fiddle :) thanks. yours is better... :) – naveen Aug 12 '12 at 18:17
  • 1
    Ok... Not having any cognitive dissonance on that comment... `;)` – Jared Farrish Aug 12 '12 at 18:18
  • @naveen that worked – may I ask why I don't need it – i was following: [http://stackoverflow.com/questions/6997895/difference-between-relative-and-absolute] in an attempt to understand positions. How do I keep the light blue box 20px from the top of the red one? – Michael Aug 12 '12 at 18:24
  • @naveen actually I think I understand. I add padding to the outer div? – Michael Aug 12 '12 at 18:26
  • thats one way of doing it... please try to read box model in css. it will help http://css-tricks.com/the-css-box-model/ – naveen Aug 12 '12 at 18:28