折叠嵌套DIV的边框

3

我有一个关于嵌套 DIV 样式的问题(请看这里的示例)。

我有一些嵌套的 DIV(带有 class="box"),它们是动态渲染的,例如:

<div class="box" id="1">
  other content
  <div class="box" id="2">
    <div class="box" id="3">
    </div>
  </div>
  other content
  <div class="box" id="4">
  </div>
</div>
other content

我希望这些 DIV 底部有边框:

<style>
div.box {border-bottom: solid 1px gray;}
</style>

问题在于,当两个嵌套的DIV底部边框相邻时(例如box 2和3或box 1和4),结果是一个高度为2(或更多像素)的灰色线条。
如果它们相邻,是否可能折叠嵌套DIV的边框?
我尝试添加border-collapse:collapse,但没有帮助。
4个回答

10

border-collapse属性仅适用于表格(table)内联表格(inline-table)元素。

尝试为.box元素添加margin-bottom属性,并使用负值来重叠边框,如下所示:

此处有示例

div.box {
    border-bottom: solid 1px gray;
    margin-bottom: -1px;
}

1
边框合并不起作用,我在您的JsFiddle中让它工作了,但您可能需要更改它,因为您的DIV是动态创建的。
div.box > div.box {
    border-bottom: solid 1px gray;
}

div.box > div.box > div.box:last-child {
    border-bottom: none;
}

:last-child 不考虑类名,只有在父元素的最后一个子元素匹配 div.box 时才能生效。 - Hashem Qolami
虽然公平地说,如果所有的孩子都是 div.box,那么使用 :last-child 也可能没有问题。但这只是需要记在心里的一点小细节。 - BoltClock
顺便说一句,other content可能会出现在第四个.box元素之后(http://jsfiddle.net/hashem/wP3CB/3/),在这种情况下,该框应有一个边框。 - Hashem Qolami

0

CSS属性border-collapse仅适用于表格...

如果您正在使用

,则可以使用CSS3的:last-child选择器来禁用最后一个.box元素上的边框

例如:

box .box:last-child{border:none;}

1
再次说明,:last-child 伪类表示其父元素的最后一个子元素,仅在父元素的最后一个子元素匹配 .box 时才起作用。 - Hashem Qolami

0

有很多方法可以做到这一点:

1)使您的div表现得像表格\表格单元格元素。

HTML

<div class="wrapper2">
    <div class="row"></div>
    <div class="row"></div>
</div>

SCSS

.wrapper2 {
    display: table; border-collapse: collapse; margin-bottom: 15px;
    .row {
        width: 200px; height: 100px; background: green; border: 1px solid red; display: table-cell;    
    }
}

2) 只需选择所需的 div 并从一侧移除边框

HTML

<div class="wrapper">
    <div class="row"></div>
    <div class="row"></div>
    <div class="clearfix"></div>
</div>

SCSS

.wrapper {
    width: 404px; margin-bottom: 15px;
    .row {
        width: 200px; height: 100px; background: green; border: 1px solid red; float: right;
        &:first-child { border-left: 0; }
    }
    .clearfix { clear: both; }
}

3) 重叠的div

HTML

<div class="wrapper3">
    <div class="row"></div>
    <div class="row move-left"></div>
    <div class="clearfix"></div>
</div>

SCSS

.wrapper3 {
    width: 404px; margin-bottom: 15px;
    .row {
        position: relative; width: 200px; height: 100px; background: green; border: 1px solid red; float: left;
        &.move-left { left: -1px }
    }
    .clearfix { clear: both; }
}

jsfiddle上的所有3个例子

只需选择适合您的项目的内容


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接