Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have <em> tag produce non-italicized text in an italic context

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.

like image 549
ngc5194 Avatar asked Oct 31 '25 05:10

ngc5194


2 Answers

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>
like image 95
dippas Avatar answered Nov 01 '25 19:11

dippas


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>
like image 36
Quentin Avatar answered Nov 01 '25 18:11

Quentin