嵌套div:我如何获得重叠边框?

Kur*_*UXD 4 html css

下图显示了所需的结果:

Desider结果

在我到达的地方下面position: relative:

<div class="tags-container">
    <div class="tag">Pizza</div>
    <div class="tag">Spaghetti</div>
    <div class="tag">Mandolino</div>
    <div class="tag">Pizza</div>
    <div class="tag">Spaghetti</div>
    <div class="tag">Mandolino</div>
    <div style="clear: both"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
.tags-container {   
    border: 1px solid #ff0000;
    width: 300px;
}
.tag {
    float: left;
    position: relative;
    top: -1px;
    left: -1px;
    padding: 5px;
    border: 1px solid #ff0000;
}
Run Code Online (Sandbox Code Playgroud)

http://www.lucagiorcelli.it/test/testing-borders.html

Has*_*ami 8

您可以将top/left重置border0和使用top属性为负值margin-top以实现结果.

实际上,没有必要使用重置边框.

虽然相对定位会在流中保留空间以防止更改布局,但边距会逐字地移动元素.

因此,您可以margin.tag元素添加负顶部/左侧.但是,在最后一行的元素底部会有一个额外的边框.

为了将边界向上移动,您可以将虚拟子项附加到该元素中,并为该元素.tags-container使用负底部margin.

由于您<div>.tags-container清除浮点数的最后使用了一个元素,因此您也可以将所需的负边距应用于该元素.

<div class="tags-container">
  <div class="tag">Pizza</div>
  <div class="tag">Spaghetti</div>
  <!-- other .tag elements... -->
  <div style="clear: both"></div> <!-- Apply negative margin to this element -->
</div>
Run Code Online (Sandbox Code Playgroud)
.tag {
  float: left;
  margin-top: -1px;
  margin-left: -1px;
  padding: 5px;
  border: 1px solid #ff0000;
}

.tags-container div:last-child {
  margin-bottom: -1px; /* This negative margin overlaps the bottom border */
}
Run Code Online (Sandbox Code Playgroud)

工作演示.


或者,您可以使用::after伪元素作为.tags-container清除浮动的最后一个子元素并应用负边距:

.tags-container:after {
  content: "";
  display: block;
  clear: both;
  margin-bottom: -1px;
}
Run Code Online (Sandbox Code Playgroud)

更新的演示.

  • 唯一不起作用的情况是当一行长于前一行时... http://jsfiddle.net/mendesjuan/ZpwxH/如果省略底部边框而不是你修复那个案例并打破原来的:) (2认同)