Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 552
M K Avatar asked Nov 14 '11 12:11

M K


People also ask

How do I apply a CSS only to a div?

Put a scoped stylesheet WITHIN the div. You can use @import to use external styles. Note, for browsers that don't support it, it will apply the style to the entire page. So you probably just want to add an id to the div you want and style with that, for compatibility.

What CSS selector should we use if we want to select all elements but not the specified class or selector?

In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector.

What is the important rule in CSS and why should you generally avoid it?

important rule is to include another ! important rule on a declaration with the same (or higher) specificity in the source code - and here the problem starts! This makes the CSS code confusing and the debugging will be hard, especially if you have a large style sheet!


1 Answers

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 */
}
like image 163
Frexuz Avatar answered Sep 26 '22 03:09

Frexuz