使用:不与相邻选择器结合使用

时间:2017-05-19 14:59:34

标签: html css css-selectors

我有这样的HTML:

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

我想要&#34;文字的背景&#34; div是白色的。但是,如果没有&#34;拇指&#34;之前的div因为div不会永远存在。

我意识到我可以做这样的事情:

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

因此将所有文本背景颜色为白色,然后覆盖在其前面具有拇指div的那些背景。

但我想知道是否可以做类似的事情:

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

只针对&#34;文本&#34;一举两得。 div没有前面的&#34;拇指&#34; DIV。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

您可以使用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。

答案 1 :(得分:0)

你提到的方式已经是只有当没有前面的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>