ED209
ED209

Reputation: 638

Margin: Auto wont work in HTML/CSS

Wonder if anyone can help me I am trying to centre a div with another div on a HTML page. The first div will centre fine, but no matter what i do with the div inside the parent div will not centre using 'margin:auto' in my CSS.

Below is my HTML:-

<div class="jumbotron">
  <div class="container">

  </div>
</div> 

and here is my CSS:-

.jumbotron {
    position: relative;
    margin: 0 auto;
    width: 1000px;
    height: 600px;
    background-color: #5a9a9a;
}

.jumbotron .container {
    position: absolute;
    margin: auto;    
    background-color: #5a5a5a;
    width: 500px;
    height: 500px;
}

Upvotes: 0

Views: 62

Answers (5)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

The margin: auto works only on staticly positioned elements. So either remove position: absolute; from your .jumboptron .container, or use:

.jumbotron .container {
    position: absolute;
    background-color: #5a5a5a;
    width: 500px;
    height: 500px;
    left: 50%;
    margin-left: -250px;
}

Upvotes: 1

Michael Jones
Michael Jones

Reputation: 2272

The problem is position: absolute. As you can see that absolute has to be positioned using actual percentages or pixels.

Now I made a little JSFIDDLE for you to see.

Upvotes: 1

user2072826
user2072826

Reputation: 536

take out

position: absolute;

on

.jumboptron .container

Upvotes: 1

Doug
Doug

Reputation: 2610

Remove position: absolute; from .jumbotron .container

Here is a JSFiddle to demonstrate.

Upvotes: 1

zgood
zgood

Reputation: 12571

Remove position:absolute; from .jumbotron .container

margin auto will not work with absolutely positioned elements

Upvotes: 1

Related Questions