streetlight
streetlight

Reputation: 5968

'If not' CSS Selectors

So this may be ambitious, but I'm trying to solve the following problem with CSS only:

.this-class[if-is-not-a-table], .this-class .something-else { 
    border: 1px solid red;
}

Basically, I'm trying to find a way to use advanced CSS selectors to only apply a style dependent on whether or not it is NOT something else. Like apply this but only if it's not on a table element. Is this possible?

NOTE: Also, this is for IE 8, so if this can be backwards compatible at all that'd be amazing!

Upvotes: 29

Views: 1865

Answers (5)

BoltClock
BoltClock

Reputation: 724502

You can use the :not() pseudo-class, but IE8 does not support it:

.this-class:not(table), .this-class .something-else { 
    border: 1px solid red;
}

Thankfully, getting it to work for IE8 is trivial — simply apply the style to any elements with .this-class, and override it for the ones that are tables instead:

.this-class, .this-class .something-else { 
    border: 1px solid red;
}

table.this-class {
    border: none;
}

Notice that the .this-class .something-else part of your first rule remains completely separate, matching descendants of .this-class regardless of what type of element it is. If that is intended, you can leave that portion unchanged. Otherwise, if you want the styles to apply to descendants of .this-class with the same condition, you will need to repeat the condition accordingly.

Using :not():

.this-class:not(table), .this-class:not(table) .something-else { 
    border: 1px solid red;
}

And using an override (for IE8):

.this-class, .this-class .something-else { 
    border: 1px solid red;
}

table.this-class, table.this-class .something-else {
    border: none;
}

Upvotes: 51

display-name-is-missing
display-name-is-missing

Reputation: 4409

:not() is what you're looking for:

In your case it's:

.this-class:not(table), .this-class .something-else {

As @ajp15243 noted, :not() isn't supported in IE8 and lower.

Upvotes: 12

Jeepstone
Jeepstone

Reputation: 2601

AFAIK :not is not supported in IE8

The best I can offer is:

.this-class { 
    border: 1px solid red;
}
table.this-class {
    border: 1px solid black;
}

Upvotes: 9

decho
decho

Reputation: 534

You can use the :not selector.

.this-class:not(table) { border: 1px solid red }

Jsfiddle example

Upvotes: 1

agrm
agrm

Reputation: 3852

You can use the :not() selector. In other words:

.this-class:not(table), .this-class .something-else { 
    border: 1px solid red;
}

A generic example: JSFiddle

Upvotes: 4

Related Questions