【问题标题】:Using :not in conjunction with adjacent selectors [duplicate]使用 :not 与相邻的选择器[重复]
【发布时间】:2017-05-19 23:14:46
【问题描述】:

我有这样的 HTML:

<div class="parent">
    <div class="thumb">...</div>
    <div class="text">...</div>
</div>

我希望“文本”div 的背景为白色。但前提是它前面没有“拇指” div,因为该 div 不会一直存在。

我意识到我可以这样做:

.parent .text {background-color: #fff;}
.parent .thumb + .text {background-color: transparent;}

所以将所有文本背景涂成白色,然后覆盖前面有拇指 div 的那些。

但我想知道是否可以这样做:

.parent :not(.thumb +) .text {background-color: white;}

当没有前面的“thumb”div 时,只针对“text”div,用一块石头杀死两只鸟。有什么想法吗?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    您可以使用 SASS 在 CSS 中使用条件(if/else):

    $type: monster;
    p {
      @if $type == ocean {
        color: blue;
      } @else if $type == matador {
        color: red;
      } @else if $type == monster {
        color: green;
      } @else {
        color: black;
      }
    }
    

    检查documentation

    或者,您可以根据需要使用 JavaScript/jQuery 来添加/删除类。

    标准 CSS 没有实际的 if/else。

    【讨论】:

      【解决方案2】:

      你提到的方式已经是只有在没有前面的div时才定位它的方式; .thumb + .text {} 样式.thumb 元素紧接在.text 元素之前适用:

      .parent {
          background: grey;
          border: 1px solid red;
          margin-bottom: 30px;
      }
      
      .text {
          background: purple;
      }
      
      .thumb + .text {
          background: white;
      }
      <div class="parent">
          <div class="thumb">...</div>
          <div class="text">White bg</div>
      </div>
      
      <div class="parent">
          <div class="text">White bg</div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-20
        • 2011-03-25
        相关资源
        最近更新 更多