Change a single word background in a paragraph with CSS only (without changing HTML)

As a part of my study project, I need to change the background of a single word ("adventure") inside a paragraph. I'm not allowed to change HTML code, can use CSS only.

<p class="section_text">
  Welcome to adventure!
</p>

The only idea I have is to set a background to a pseudo-element ::after and play with position relative/absolute, but it doesn't feel right.

.section_text {
  position: relative; }

.section_text::after {
  content: "adventure";
  background-color: #04128f;
  color: #0f0;
  width: 65px;
  height: 20px;
  position: absolute;
  top: 0;
  left: 90px; }

Are there any smart ways to do that (it should work in the last version of Chrome)? P.S. Can not use JS or jQuery neither. Exclamation sign background shouldn't be changed.

Upvotes: 3

Views: 1767

Answers (2)

Loi Nguyen Huynh
Loi Nguyen Huynh

Reputation: 9938

Edit: to change background-color for an arbitrary position word, see zer00ne's answer above. I didn't read the question thoroughly, so I wasn't aware that the OP wants the word adventure not adventure!

The smartest way to change any arbitrary word is to wrap it inside a span tag. Here's the workaround for changing the background of the last word: From your delivered code, display: inline-block for p tag, and don't set width for ::after element.

.section_text {
  display: inline-block;
  background: #3333;
  position: relative;
}

.section_text::after {
  content: 'adventure!';
  position: absolute;
  right: 0;
  height: 100%;
  z-index: 1;
  background: red;
}
<p class="section_text">
  Welcome to adventure!
</p>

Upvotes: 0

zer00ne
zer00ne

Reputation: 43880

  1. Set an intrinsic font-size to the :root selector. ex. :root {font-size: 5vw}. This makes the font responsive to viewport width.

  2. Make the background of <p> the highlight color (ex red) and set its width: max-content.

  3. Next <p> needs position: relative and then z-index: -1

  4. Add two pseudo elements to <p>

    p::before {content: 'Welcome to';...}
    /*and*/ 
    p::after {content: '!';...}
    

    Assign position: absolute, z-index: 1, and background: white

  5. Finally set right: 0to p::after so the exclamation mark is always at the very end

Note: the property/value content: 'Welcome to\a0'; on p::before selector has \a0 at the end. This is the CSS entity code for a non-breaking space (HTML entity: &nbsp;)

:root {
  font: 400 5vw/1 Consolas
}

p {
  position: relative;
  width: max-content;
  z-index: -1;
  background: red;
}

p::before {
  position: absolute;
  content: 'Welcome to\a0';
  background: white;
  z-index: 1
}

p::after {
  position: absolute;
  content: '!';
  background: white;
  z-index: 1;
  right: 0
}
<p>Welcome to adventure!</p>

Upvotes: 3

Related Questions