【问题标题】:How to apply spacing between divs without having an excess at the right or the left?如何在 div 之间应用间距而不在右侧或左侧有多余的空间?
【发布时间】:2011-06-27 00:11:00
【问题描述】:

这是我面临的常见问题之一,我最终会添加令人讨厌的额外间隔标记,以避免在右侧或左侧有边距(如果是垂直菜单,也可以在顶部或底部)。

是否有一种干净的 css 方法来避免为最后一个元素应用边距?


【问题讨论】:

标签: css


【解决方案1】:

使用:not(:last-child)

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

或者,

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

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

或者,

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

或者,

.box {
    margin: 0 5px;
}

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

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

兼容性:

【讨论】:

  • 谢谢,看起来很干净,真正的问题是:主流浏览器是否支持它?再次感谢。
  • @David 你关心哪个版本的IE?
  • @Harpyon,这需要使用.box 的另一个选择器not() 意味着只使用一个。虽然如果正在设置其他 CSS 属性,删除 not() 会更有效。
  • 这很有趣,您发布了几乎所有变体,除了应该实际使用的变体(感谢 IE7/8)。不过,+1
【解决方案2】:

你应该使用:

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

这比使用:last-child(来自CSS 3)要好,因为IE7/8 不支持,而:first-child(来自CSS 2)支持。

【讨论】:

    【解决方案3】:

    我想你可以试试这个,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;
    }
    

    你是这个意思吗?

    【讨论】:

      【解决方案4】:

      根据Quirks Mode :last-child 在 IE6/7/8 中不受支持,因此另一种方法是对最后一个元素应用另一个类,然后覆盖 CSS 中的边距。

      【讨论】: