如果PURE CSS中存在同级元素,则有条件地设置样式 [英] Conditionally set style if sibling element exists in PURE CSS

查看:126
本文介绍了如果PURE CSS中存在同级元素,则有条件地设置样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构,其中第二个元素可能会或可能不会出现。

I have the following structure, where second element may or may not appear.

<div class="wrapper">
    <div class="firstElement"></div>
    <div class="secondElement"></div>
</div>

我想在 .firstElement 仅在 .secondElement 存在的情况下。

I want to conditionally set styles on .firstElement ONLY if .secondElement exists.

是否可以使用PURE CSS做到这一点?

Is there a way to do this with PURE CSS? With either sibling selectors/ parent selectors?

谢谢!

推荐答案

一般来说,没有。 CSS会向前/向下读取DOM-而不会向后/向上读取。但是使用此标记,您可以使用:not(:last-child)

In general, no. CSS reads forwards/down the DOM - it won't read backwards/up. But with this markup, you could use :not(:last-child)

.firstElement:not(:last-child) {
  color: red
}

<div class="wrapper">
    <div class="firstElement">target this</div>
    <div class="secondElement"></div>
</div>

<div class="wrapper">
    <div class="firstElement">not this</div>
</div>

这篇关于如果PURE CSS中存在同级元素,则有条件地设置样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆