简体   繁体   中英

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

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>

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 */
}

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

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.

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM