-1

I'm trying to highlight some words inside a h1 header.

And I'm using a CSS pseudo-element to achieve that.

But how do I make the CSS pseudo element appear behind the word "Piece of Cake" and nothing else?

At the moment it stretches across the entire heading, which I do not want.

.yellow-highlight {
  white-space: nowrap;
}

.yellow-highlight:before {
  content: " ";
  position: absolute;
  width: 100%;
  height: 1em;
  left: -0.25em;
  top: 0.1em;
  padding: 0 0.25em;
  background-color: #FEFDBD;
  transform: rotate(-2deg);
  z-index: -1;
}
<h1>Blah Blah Blah Blah Blah Blah Blah <span class="yellow-highlight">Piece of Cake</span></h1>
TinyTiger
  • 1,801
  • 7
  • 47
  • 92
  • if you need the solution, Its easy to achieve this without psuedo class . – Dhara Aug 20 '21 at 01:55
  • 1
    Does this answer your question? [Position absolute but relative to parent](https://stackoverflow.com/questions/10487292/position-absolute-but-relative-to-parent). Also see [Position an element relative to its container](https://stackoverflow.com/questions/104953/position-an-element-relative-to-its-container). – showdev Aug 20 '21 at 02:11

1 Answers1

3

Just add position: relative; to your .yellow-highlight selector.

.yellow-highlight {
  position: relative;
  white-space: nowrap;
}

.yellow-highlight:before {
  content: " ";
  position: absolute;
  width: 100%;
  height: 1em;
  left: -0.25em;
  top: 0.1em;
  padding: 0 0.25em;
  background-color: #FEFDBD;
  transform: rotate(-2deg);
  z-index: -1;
}
<h1>Blah Blah Blah Blah Blah Blah Blah <span class="yellow-highlight">Piece of Cake</span></h1>
wizzfizz94
  • 1,288
  • 15
  • 20
  • 1
    Just for reference: `absolute` positions an element "relative to its closest positioned ancestor" ([MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/position#values)). Explicitly declaring `position:relative` makes the `` a "positioned ancestor" of the pseudo-element. Also see [positioning contexts](https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#positioning_contexts). – showdev Aug 20 '21 at 02:09