skip to Main Content
/* CSS */
em {font-style: italic; background yellow}
::autonomous-not-child-of-a-p-element-? :: em {font-style:normal; background gray}

Given two situations both using <em> differently, in need to be styled differently.
The first case contains a paragraph element and within it one or multiple <em> italic styled words:

<p>...</p>
<p>A paragraph with a <em>word or two</em> in italic emphasis within the paragraph.</p>
<p>...</p>

The second paragraph contains a <em> wrapping over an entire paragraph, becoming itself a paragraph, that needs to be styled differently:

<p>...</p>
<em>An entire paragraph in its entirety in italic emphasis.<em>
<p>...</p>

Is there a way to restyle the last <em> differently automatically, when it spans an entire paragraph and is not a child of a <p> element?

5

Answers


  1. You can use hierarchy/inheritance in css to target the em in p tag and normal em element to target the em tag.

    em { color: #F0F; }
    p em { color: #F00; }
    <p>...</p>
    <p>A paragraph with a <em>word or two</em> in italic emphasis within the paragraph.</p>
    <p>...</p>
    
    <hr />
    
    <p>...</p>
    <em>An entire paragraph in its entirety in italic emphasis.<em>
    <p>...</p>

    Also, this can be helpful to understand.

    Hope, this helps.

    Login or Signup to reply.
  2. em { color: #F0F; }
    p em { color: #F00; }
    <p>...</p>
    <p>A paragraph with a <em>word or two</em> in italic emphasis within the paragraph.</p>
    <p>...</p>
    
    <hr />
    
    <p>...</p>
    <em>An entire paragraph in its entirety in italic emphasis.<em>
    <p>...</p>
    Login or Signup to reply.
    1. with the help of Specificity, you can describe the Css like:
        em {font-style:normal; background: gray}
        p em {font-style:italic; background: white}
    
    1. using CSS next-sibling combinator (+) :
        p + em {font-style:normal; background: gray} /* this will select em next to P tag */
    
    1. providing class name

    refer:
    https://www.w3schools.com/cssref/sel_element_pluss.php

    Login or Signup to reply.
  3. in order to solve this issue. You can simply use the not selector to select every em element not a child of a p element.

    If you have issues with this answer or if I didn’t totally answered it, let me know !

    :not(p) > em {
        properties
    }
    
    Login or Signup to reply.
  4. So if you have only these two conditions then you can try this solution

    Solution

    1. This will target only the child of p tag

      p>em {
      color: #ff0000;
      font-size:30px;
      }

    2. If em is below

      tag then this code will target every em that is below

      tag

      p+em {
      color: #ff0000;
      font-size:30px;
      }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search