zigojacko
zigojacko

Reputation: 2053

Getting auto margin to work for center aligning div

I've overlooked something obvious and simple for sure here but I'm going to have to admit defeat and ask on SO for now.

I've made a JSfiddle.

A simple one. Simply trying to center align the div class ratings inside it's parent container. I haven't managed to get any auto margins to work at all after numerous faffing with it.

The code below:-

CSS

.caption {
    padding: 9px;
    width: 100%;
    display: block;
}

.ratings {
    width: 100%;
    overflow: hidden;
    margin: 3px auto;
    display: block;
}

Markup

<div class="caption">
    <h2 class="product-name"><a href="#">Product Title</a></h2>

    <div class="ratings">
        <div class="rating-bar">
        <div class="rating-box"></div>
        <div class="rating" style="width:100%"></div>
        <div class="rating-fill"></div>
    </div>
        <span class="amount"><a href="#">(2)</a></span>
    </div>
</div>

Upvotes: 0

Views: 64

Answers (4)

omma2289
omma2289

Reputation: 54619

.ratings is just a container so you can remove the float from .rating-bar and use display: inline-block instead, then set text-align:center on .ratings

.ratings {
    text-align: center;
}

.ratings .rating-bar{
    display: inline-block;
    /*float:left; remove this*/
}

Demo fiddle

Upvotes: 1

seemly
seemly

Reputation: 1090

By default, a block level element has a width of 100%, so defining a width of 100% is irrelevant in this case.

Basically, your child element needs to have a defined smaller width than it's parent, in order to be able to center horizontally.

e.g;

.ratings {
  width:50%;
  margin:0 auto;
}

Upvotes: 0

Barney
Barney

Reputation: 16456

It's got a width of 100%, which means the auto value computes to 0 pixels. You will need to either:

1) Specify the width you actually want.

2) Make it shrink-to-fit with display: inline-block, then wrap it in a block with text-align: center

Upvotes: 0

Morgan T.
Morgan T.

Reputation: 1937

You need to set a specific width e.g. 150px on the Ratings class instead of 100% Otherwise, 100% width means the calculation of margins = 0 (none left for margins)

Upvotes: 0

Related Questions