开发者

how to center items dynamically inside a div

开发者 https://www.devze.com 2023-03-14 15:51 出处:网络
开发者_如何转开发given a container with items inside like so: <div id=\"container\"> <div class=\"item\">Item</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


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;
}


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号