Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle a CSS property in nested elements

Tags:

css

Without using Javascript, is there a way to make a CSS property toggle on and off through nested elements.

The problem I'm trying to solve is that I have a number of tags and classes which make some text italic (<em>, <blockquote>, <cite>, <q>, <dfn>, and some other classes), and when one of these is inside another one of these, the italicisation needs to toggle.

<blockquote>
    And so the man said, <q>That's not from <cite>Catcher In The Rye</cite>, dear
    fellow!</q>, can you believe that?!
</blockquote>

Should render as:

And so the man said, "That's not from Catcher In The Rye, dear fellow!", can you believe that?!

The CSS I've got for this is getting a bit messy:

q, em, dfn, cite, blockquote {
    font-style: italic;
}
q q, q em, q dfn, q cite,
em q, em em, em dfn, em cite,
dfn q, dfn em, dfn dfn, dfn cite,
cite q, cite em, cite dfn, cite cite,
blockquote q, blockquote em, blockquote dfn, blockquote cite {
    font-style: normal;
}

...and I'm pretty sure that won't even work past one level of nesting (as in my example).

Is there a way I can do this without have to list every permutation of the tags?

like image 317
nickf Avatar asked Nov 14 '22 16:11

nickf


1 Answers

I couldn't tell you which browsers (if any) implement the CSS3 :not pseudo-class, but if we see it supported sometime it seems like we can do:

q:not(q, em, dfn, cite, blockquote), 
em:not(q, em, dfn, cite, blockquote), 
dfn:not(q, em, dfn, cite, blockquote), 
cite:not(q, em, dfn, cite, blockquote), 
blockquote:not(q, em, dfn, cite, blockquote) { font-style: italic; }

It's anyone's guess as to how browsers will implement this when they do, so it might not work more than 2 levels deep (like your example).

Other than that, unfortunately I can't think of another pure CSS solution.

like image 197
Eric Wendelin Avatar answered Jan 11 '23 03:01

Eric Wendelin