How can i affect all content within a tag except a specific child tag

30 Views Asked by At

i have the following code example


i am trying to affect all h1 content except the <strong> content

i tried using the child combinator and the :first-child selector and couldnt, thanks in advance

h1 {
  background-color: aqua;
}


/* option 1 */

div h1:not( > strong) {
  background-color: yellow;
}


/* option 2 */

div h1:not(:first-child) {
  background-color: yellow;
}
<div>
  <h1>
    <strong>STRONG Line #1, Intended to stay the same aqua</strong><br> Line #2, Intended to be Yellow.
  </h1>
</div>
<span>Line #3, not in the div at all.</span>

here is the testing console developer.mozilla

3

There are 3 best solutions below

0
Nick Friesen On

If you target the strong element within the h1 directly, you can style it to be different than the rest of the content. See the below as an example:

h1 {
  background-color: yellow;
}

div h1 strong {
  background-color: aqua;
}
<div>
  <h1>
    <strong>STRONG Line #1, Intended to stay the same aqua</strong><br>
    Line #2, Intended to be Yellow.
  </h1>
</div>
<span>Line #3, not in the div at all.</span>

0
Paulie_D On

Your colors seem to be round the wrong way in your CSS. If you swap them it simplifies your selectors. Essentially color the h1 background and then target the strong inside the h1.

h1 {
  background-color: yellow;
}

div h1 strong {
  background-color: aqua;
}
<div>
  <h1>
    <strong>STRONG Line #1, Intended to stay to be aqua</strong><br>
    Line #2, Intended to be Yellow.
  </h1>
</div>
<span>Line #3, not in the div at all.</span>

0
connexo On

To explain what is your problem here:

The background-color in fact does not affect the strong part, specifically, at all.

It only appears to do this, visually (!), because by default the background-color of strong is transparent, making the bg color of the surrounding h1 look like it's also the bg color of the strong element.

As soon as your strong element has an opaque bg color applied this becomes clear:

h1 {
  background-color: yellow;
}

strong {
  background-color: aqua; /* replaces the default "transparent"! */
}
<div>
  <h1>
    <strong>STRONG Line #1, Intended to stay to be aqua</strong><br>
    Line #2, Intended to be Yellow.
  </h1>
</div>
<span>Line #3, not in the div at all.</span>