I have styled the h4 tag to use an italic font styling font-style: italic;. Works fine.
Within a header, I would like to sometimes emphasize words using the em tag.
When this happens, I'd like the emphasized words to be rendered in a non-italicized font to distinguish them from the surrounding text.
What are my options?
To be clear, when using em outside of h4 headers (with non-italicized text), it should italicize the text.
Only when the surrounding text is italicized do I want em to behave differently. I'd strongly prefer to do this using just HTML and global CSS properties.
The basic philosophy is this: em should call attention to text by making it different from the text around it. I don't know how to do this in a way that's sensitive to the context of the surrounding text.
I'm wondering if there's a straightforward way to do so.
Do like this
h4 {
font-style: italic
}
h4 em {
font-style: normal /* initial */
}
<h4>hey text italic by CSS</h4>
<h4><em>hey text normal because <code>em</code> is here</em></h4>
<em>hey text by default tag</em>
CSS has no mechanism to set a rule based on the parent element's computed style.
You could use a descendant combinator and be explicit about everywhere you want it to be different:
h4 em { font-style: normal; }
Or you could use JavaScript and test each element's parent in turn…
function italic() {
var em = document.querySelectorAll("em");
em.forEach(function (em) {
var parent = window.getComputedStyle(em.parentNode).fontStyle
if (parent === "italic") {
em.style.fontStyle = "normal";
}
});
}
addEventListener("DOMContentLoaded", italic);
h4 { font-style: italic; }
<h4>This is <em>em</em></h4>
<p>How <em>em can you get? You can <em>nest! So many <em>levels</em> deep</em>.</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With