Michael
Michael

Reputation: 525

How to center div within another div?

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.

Upvotes: 1

Views: 1701

Answers (1)

codeandcloud
codeandcloud

Reputation: 55200

Just remove the position:absolute; property for #inner

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

Upvotes: 3

Related Questions