css - 没有双边框或间隙的兄弟元素的边框

标签 css sass css-selectors

<分区>

我需要实现正常的无限列表布局,每个元素周围都有一个边框。我不希望在两个元素的边界相交处出现 2-border look。我试过 a few approaches并由于 :last-child 的行为而卡住,即父元素仅将最后一个元素视为最后一个子元素。

HTML

<div class="parent">
  <div class="child">
    <span>Has proper border</span>
  </div>
  <div class="child">
    <span>Not proper border</span>
  </div>
  <p>I introduced border issue</p> <!-- Can't remove this tag -->
</div>

SCSS 和 CSS

span {
  display: inline-block;
  padding: 10px;
  border: 1px solid black;
}
.parent {
  margin: 15px 0;
  .child {
    &:not(:last-child) {
      span{ border-bottom-width: 0; }
    }
    // tried just to make things work. But it doesn't.
    &:last-child {
      span{ border-bottom-width: 1px; }
    }
  }
}

// Equivalent CSS - 
.parent .child:not(:last-child) span {
  border-bottom-wdth: 0;
}
.parent .child:last-child span {
  border-bottom-wdth: 1px;
}

最佳答案

我在 CSS(12)和 SCSS(1)中阅读了一些关于兄弟选择器的文章/问题,并应用了以下选项来实现所需的行为,同时保持相同的 HTML -

<强>1。相邻兄弟选择器(“+”)方法 - Working example

.parent {
  /* siblings approach */
  margin: 15px 0;
  $className: child;
  .#{ $className } {
    & + .#{ $className } {
      span {
        border-top-width: 0;
      }
    }
  }
}

// Equivalent CSS - 
.parent .child + child span {
  border-top-width: 0;
}

<强>2。 ":last-of-type"方法 -

// Same can be achieved using ":first-of-type"
.parent {
  /* :last-of-type approach */
  margin 15px 0;
  span {
    border: 1px solid black;
    border-bottom-width: 0;
  }
  .child:last-of-type {
    span {
      border-bottom-width: 1px;
    }
  }
}

// Equivalent CSS
.parent .child:last-of-type span {
  border-bottom-width: 1px;
}

关于css - 没有双边框或间隙的兄弟元素的边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57767999/

上一篇:jquery - Android WebView Javascript 接口(interface)与浏览器冲突

下一篇:html - 单击按钮显示蓝色矩形。此外,按钮在关闭模式后取消悬停

相关文章:

html - 自定义输入范围的处理程序

html - 如何将标题项与 HTML 和 SCSS 对齐

python - 如何使用 Selenium 和 Python 从下拉菜单中选择选项

c# - 覆盖 ASP.NET MVC 事件样式表包

css - 选择放置在另一个元素之后但不是立即放置的第一个元素

html - CSS 选择多个标签

html - 使用类将样式应用于 div 中的元素

JQuery 挑战 - 在点击事件上绘制计数标记

jquery - Kendo UI - 并排显示图表

css - Bourbon 找不到字体混合(Rails 3.2.2)