简体   繁体   中英

'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!

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;
}

: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.

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;
}

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

You can use the :not selector .

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

Jsfiddle example

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