【问题标题】:Borders for sibling elements without double border or gap [duplicate]没有双边框或间隙的兄弟元素的边框[重复]
【发布时间】:2019-09-03 16:39:29
【问题描述】:

我需要实现正常的无限列表布局,每个项目周围都有一个边框。我不想要两个元素的边界相交的 2-border 外观。我尝试了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 sass css-selectors


    【解决方案1】:

    我在 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;
    }
    

    【讨论】:

    • :last-of-type 不适用于类名,仅适用于元素(div、p 等)