CSS样式一个子div,但只有父母有一个兄弟

时间:2017-08-08 21:57:26

标签: css css3 css-selectors

我想将margin-top样式添加到.three,但前提是.one.two



.one {
  background: indianred;
  height: 100px;
  width: 100px;
}

.three {
  background: bisque;
  height: 100px;
  width: 100px;
}

.one .two + .three {
  margin-top: 20px;
}

<div class="one">
  <div class="two">hello</div>
</div>
<div class="three">there</div>


<div class="one">
</div>
<div class="three">there</div>
&#13;
&#13;
&#13;

Fiddle

可以这样做吗?感谢帮助。

1 个答案:

答案 0 :(得分:2)

据我所知,你目前最接近的是扭转逻辑并使用{​​{1}}。它是一个糟糕的替代品,可能无法满足您的需求,但可以在适当的情况下工作。

:empty
.one {
  background: indianred;
  height: 100px;
  width: 100px;
}
.three {
  background: bisque;
  height: 100px;
  width: 100px;
  margin-top: 20px;
}

.one:empty + .three {
  margin-top: 0;
}

这有点像作弊,因为它没有检查<div class="one"> <div class="two">hello</div> </div> <div class="three">there</div> <div class="one"></div><!-- Note how .one is completely empty with not even a newline --> <div class="three">there</div>是否有.one。相反,它假设.two确实有一个孩子而该孩子是.one。如果.two没有孩子,则不会应用保证金。这做了很多假设,并且在大多数情况下都没用,除非你能做出相同的假设。

唯一可以使用此方法的方法是,如果您知道.one是唯一可能的孩子,并且如果.two没有.one那么它将始终没有任何内容。没有空格,换行符或任何其他可以算作孩子的东西(评论是安全的)。

查看是否可以使用此(或类似的东西)的好方法是尝试重写您的逻辑。如果“将margin-top添加到.two,但仅当.three具有.one”时才可以重写为“从.two删除margin-top,但仅限.three 1}}为空'然后这个方法将起作用。根据您的实际需要,可能还有其他方法可以将您的逻辑重新思考为当前可行的东西。

相关问题