AnApprentice
AnApprentice

Reputation: 110950

how to center items dynamically inside a div

given a container with items inside like so:

<div id="container">

    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>   

</div>
#container {
    width: 600px;
    border: 1px solid #CCC;
}

#container .item {
    background: red;
    display:inline-block;
    width: 50px;
    height: 50px;
}

http://jsfiddle.net/zrhLt/

Is there a way with CSS (no JS) to automatically center the items with equal margins. Without having to use a table?

Thanks

Upvotes: 4

Views: 474

Answers (2)

Steve Wellens
Steve Wellens

Reputation: 20620

You could play with the margins like this:

#container {
    width: 600px;
    border: 1px solid #CCC;

}

#container .item {
    background: red;
    display:inline-block;
    width: 50px;
    height: 50px;
    margin-left: 1.4%;
    margin-right: 1.4%;
}

Play a Fiddle: http://jsfiddle.net/zrhLt/9/

Upvotes: 1

andyb
andyb

Reputation: 43823

Adding text-align:center; to the container centers all the items.

You don't want to use a table but you can still tell the browser to render it as a table :-) So how about this CSS:

#container {
    width: 600px;
    border: 1px solid #CCC;
    display: table;
    border-spacing:20px 0; /* this is the value that controls the margin */
}

#container .item {
    background: red;
    display: table-cell;
    width: 50px;
    height: 50px;
}

Upvotes: 4

Related Questions