Can you apply CSS rules, in CSS, if a div doesn't exist?

纵饮孤独 提交于 2020-11-25 13:48:17

问题


Is this possible, with CSS ?

Apply this rule if .div1 doesn't exist:

.div2{
  property: value;  
}

like

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

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

and

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

回答1:


If you know the 'unstyled' styles of the div, you could use a css sibling selector to style it one way if it follows .div1, and the 'plain' way if it doesnt - ie

.div2 {
    /* styled however you want */
}
.div1 + .div2 {
    /* 'plain' styling */
}

See the fiddle. Try removing div1 to see div2 as it would be styled without div1




回答2:


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


Apply style to .div2 if .div1 exists:

Option 1: .div2 follows directly after .div1

.div1 + .div2 {
  property: value;
}

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

.div1 ~ .div2 {
  property: value;
}

Style .div2 without .div1:

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.

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

.div2 {
  background: #fff;
}

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

/* or */

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



回答3:


NO

With CSS alone, the if conditions which check the availability of an element, is not possible. You should use JavaScript, (jQuery is recommended).

Notes: With CSS you can check some conditions of an element, like checking if an element has an attribute (like input[type=text]), or checking if an element is the first element of a list (like p:first-child), etc. But you can't check anything from the element's sibling elements, or ancestors. Also you can't check the negative conditions most of the times.




回答4:


Generally speaking, no, you can't do that.

But you may 'hack' it using CSS selectors, I'm referring to to:

  • + .something selector
  • ~ .something selector

I'd use the second selector, which is the "general sibling" selector.

Given the HTML you posted you can apply the style to the .div2 class and then reset it using the .div1 ~ .div2 selector.

So something like this:

.div1 {
  color: red;
}

.div2 {
  color: blue;
}

.div1 ~ .div2 {
  color: black;
}

In this way, with the first HTML snippet the div2 will be black and with the second snippet it will be blue.




回答5:


No, this is not possible. But you can create class "div3" and in your code determine whether DIV1 exists and in that case apply the "div3" class instead of "div2"



来源:https://stackoverflow.com/questions/8121847/can-you-apply-css-rules-in-css-if-a-div-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!