Don P
Don P

Reputation: 63728

Center a div in a section

I'm trying to center a <div> in <section>. Setting margin-left and margin-right to auto isn't working (my usual method). What am I forgetting?

jsFiddle of the problem: http://jsfiddle.net/veWKh/

Upvotes: 2

Views: 39150

Answers (6)

Web User
Web User

Reputation: 330

Try it

section {
    background-color: rgba(0,0,0,0.2);
}

div {
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}

Upvotes: 2

Kevin Lynch
Kevin Lynch

Reputation: 24723

For margin:auto to work you need to give the div a set width eg:

div {
    width:100px;
    margin: 0 auto;
}

Upvotes: 2

Anickyan
Anickyan

Reputation: 414

This works perfectly:

section
{
    text-align: center;
}

This will make everything centered, though. Otherwise you can just do this:

div 
{
    display:block;
    text-align:center;
    margin: auto;
}

Upvotes: 1

Antarr Byrd
Antarr Byrd

Reputation: 26141

This width of your div is not limited so what you are doing is not visible.

div {
    display:block;
    width:50%;
    background-color: #ffffff;
    margin: 0 auto;
}

Upvotes: 0

Sanjaya Liyanage
Sanjaya Liyanage

Reputation: 4746

set the width first.Other wise it will occupy the full space and setting margins will not work

div {
    width:30em; 
    margin-left: auto;
    margin-right: auto;
}

Upvotes: 0

Niels
Niels

Reputation: 49919

Setting the width, otherwise the div is display block and has a width of 100%: fiddle: http://jsfiddle.net/veWKh/1/

CSS:

section {
    background-color: rgba(0,0,0,0.2);
}

div {
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

Upvotes: 7

Related Questions