开发者

How to apply spacing between divs without having an excess at the right or the left?

开发者 https://www.devze.com 2023-03-15 06:54 出处:网络
This is one of the common issues i face and i end up having nasty additional spacer markup to avoid having a margin in the right or the开发者_运维知识库 left ( also at the top or the bottom if it\'s a

This is one of the common issues i face and i end up having nasty additional spacer markup to avoid having a margin in the right or the开发者_运维知识库 left ( also at the top or the bottom if it's a vertical menu ).

Is there a clean css way to avoid applying the margin for the last element?


How to apply spacing between divs without having an excess at the right or the left?


Use :not(:last-child).

.box:not(:last-child) {
    margin-right: 10px;
}

Or,

.box:not(:first-child) {
    margin-left: 5px;
}

.box:not(:last-child) {
    margin-right: 5px;
}

Or,

.box {
    margin-right: 10px;
}
.box:last-child {
    margin-right: 0px;
}

Or,

.box {
    margin: 0 5px;
}

.box:first-child {
    margin-left: 0;
}

.box:last-child {
    margin-right: 0;
}

Compatibility:

  • CSS2 :not pseudo-class
  • CSS2 :first-child pseudo class
  • CSS3 :last-child pseudo class


You should use:

.box {
    margin-left: 20px
}
.box:first-child {
    margin-left: 0
}

This is better than using :last-child (from CSS 3), because that's not supported in IE7/8, whereas :first-child (from CSS 2) is.


i guess you can try this one, http://jsfiddle.net/yuliantoadi/g98Wq/

html :

<div class="container">
<div class="box">
    box 1
</div>
<div class="box">
    box 2
</div>
<div class="box">
    box 3
</div>
    <div style="clear:both"></div>
</div>

css:

.box{
    width:32%;
    float:left;
    background:red;
    margin-left:2%;
}
.container {
    background:blue;
    padding:2%;
}
.container .box:first-child{
    margin-left:0;
}

is that what you mean?


According to Quirks Mode :last-child isn't supported in IE6/7/8 so an alternative could be to apply another class to the last element and then just override the margin in the CSS.

0

精彩评论

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