【问题标题】:CSS Multiple grouped elements with marginsCSS 多个带边距的分组元素
【发布时间】:2011-09-28 15:13:24
【问题描述】:

获取此 HTML:

<div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
    <div class="block">Hello</div>
</div>

使用配套的 CSS:

div.block
{
    float: left;
    width: 100px;
    height: 100px;
    margin: 1px;
    background: red;
}

这样做的结果是四个块,它们之间有 2 像素 的空间(距左侧块的右边距 1px,距右边块的左边距 1px)。

有没有办法可以达到与边框折叠类似的效果? IE。我希望相邻块之间只有一个像素的边距。

这是我经常遇到的更复杂情况的一个基本示例,我不想通过任何类似于仅将 margin-left 设置为 1 像素等的方法来绕过它。

【问题讨论】:

    标签: html css margin


    【解决方案1】:

    有多种方法

    其中一个是

    div.block
    {
        float: left;
        width: 100px;
        height: 100px;
        margin: 1px 1px 1px 0;
        background: red;
    }
    div.block:last-child {
        margin: 1px 0 1px 0;
    }
    

    另一个是

    div.block+div.block { margin-left: 1px; }
    

    您可以检查demo的双向here

    【讨论】:

    • 我喜欢后一个选项,这是否得到大力支持?
    • 支持IE8+,safari buggy,opera 9.5+,chrome 2.0+,见reference.sitepoint.com/css/adjacentsiblingselector
    • @MartyWallace,不,尽管大多数现代浏览器现在都支持,但它们并未得到广泛支持。如果旧浏览器需要兼容,您可以借助 javascript。
    【解决方案2】:

    如何使用 CSS 选择器 :first-child and :last-child 更改第一个和最后一个 &lt;div&gt;

    div.block
    {
        float: left;
        width: 100px;
        height: 100px;
        margin: 2px 1px 2px 0;
        background: red;
    }
    div.block:first-child {
        margin-left: 2px;
    }
    div.block:last-child {
        margin-right: 2px;
    }
    

    【讨论】:

    【解决方案3】:

    如果你可以改变标记本身,那么我想我们可以有一个跨浏览器兼容的解决方案:

    <div class="block"> <div class="block_2"></div> </div>
    

    然后像这样应用css:

    div.block{float: left; width: 100px; height: 100px; }
    div.block_2{width:99px; height:100px; background-color:red}
    

    【讨论】:

      【解决方案4】:

      为最后一个块分配一个名为“last”的类。 将每个块的边距设置为 1px。 将具有最后一个类的块的 margin-right 设置为 0。 .block.last { 边距右:0px; }

      像 forst-child 和 last-child 这样的伪选择器没有得到很好的支持,所以我认为这是你最好的选择。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-04
        • 1970-01-01
        • 2011-12-06
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多