如果div不存在,可以在CSS中应用CSS规则吗? [英] Can you apply CSS rules, in CSS, if a div doesn't exist?

查看:103
本文介绍了如果div不存在,可以在CSS中应用CSS规则吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用CSS可以吗?

如果.div1不存在,请应用此规则:

Apply this rule if .div1 doesn't exist:

.div2{
  property: value;  
}

喜欢

<div class="div1">
...
</div>

<div class="div2">
 <!-- it exists, so do nothing -->
</div>

<div class="div2">
 <!-- it doesn't exist, apply the css -->
</div>

推荐答案

是否存在?您的问题使我感到困惑:)

Exists, or doesn't exist? Your question confuses me :)

如果.div1存在,则将样式应用于.div2:

Apply style to .div2 if .div1 exists:

选项1: .div2.div1

.div1 + .div2 {
  property: value;
}

选项2: .div2作为兄弟姐妹紧随.div1:

Option 2: .div2 follows .div1 as a sibling:

.div1 ~ .div2 {
  property: value;
}


不含.div1的样式.div2:


Style .div2 without .div1:

这有点骇人听闻,但您可以反其道而行之. 正常设置.div2的样式,然后使用上面的选择器覆盖样式.

It's a bit of a hack, but you could do the reverse. Style .div2 normally, and then override the styling with the selectors above.

如果.div1不存在,则.div2将使用常规样式.

If .div1 doesn't exist, .div2 gets the normal styling.

.div2 {
  background: #fff;
}

.div1 + .div2 {
  background: #f00; /* override */
}

/* or */

.div1 ~ .div2 {
  background: #f00; /* override */
}

这篇关于如果div不存在,可以在CSS中应用CSS规则吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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