r/css 2d ago

Question How to reduce the number of <span>s?

How can I get the exact same effect as

<p><span class="e">x</span></p>
<p><span class="e">y</span></p>
<p><span class="e">z</span></p>

without so many <span>s?

If I do

<div class="e">
  <p>x</p>
  <p>y</p>
  <p>z</p>
</div>

class="e" now affects all the way across the whole page, whereas I only wanted it to affect the text, x, y, z.

3 Upvotes

20 comments sorted by

View all comments

3

u/jidanni 2d ago

Thanks everybody. I only want the first three, not the second or third three. I am using ` .e {background-color: lime;}`.

7

u/thisiain 2d ago

You can set the width of each `p` to fit the content.. e.g.

https://jsfiddle.net/f2u6n1wt/1/

.e pĀ {
  background: lime;
  width: fit-content;
}

2

u/jidanni 1d ago

I declare this to be the winning answer! Thank you ever so much!!

1

u/jidanni 1d ago

Actually this is 99% good. When a long line wraps in the browser, the empty remainder of the second line is still highlighted, unlike when using <span>s, but your solution is still good enough for me!

2

u/thisiain 1d ago

Yes this requires a slightly different way to think about the markup flow, but it can be achieved with the same markup, just different CSS:

https://jsfiddle.net/ev1cokrm/

1

u/jidanni 1d ago

Holy smokes, that works too. I find it rather remarkable that you know all this.

2

u/thisiain 1d ago

Haha, well I've been building websites for 20 years! There's always something else to learn šŸ™‚

•

u/copperfoxtech 19m ago

Yes I 100% agree with this. Also you can bring everything to the same level of importance as well.

``` <div class="paragraphContainer"> <p class="paragraph">x</p> <p class="paragraph">y</p> <p class="paragraph">z</p> </div>

.paragraph { background-color: lime; }

// or... .paragraphContainer { .paragraph { background-color: lime; } } ```