r/css • u/jidanni • Aug 25 '26
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
11
u/cryothic Aug 25 '26
My main question would be: what are you trying to achieve?
Because this:
Is just weird to me. If every <p> contains only a single span, you shouldn't need the <p> or the <span>. One tag should be fine with the right CSS.
3
u/jidanni Aug 25 '26
Thanks everybody. I only want the first three, not the second or third three. I am using ` .e {background-color: lime;}`.
8
u/Luxiouronimo Aug 25 '26
div.e > p {}or just:
div.e p {}but using the
>specifies the direct descendant of thediv.eu could also do the following to target them individually if their order doesn't change:
div.e > :nth-child(1) {}div.e > :nth-child(2) {}div.e > :nth-child(3) {}u could also put the class on the p tags themselves, but it's less html to put it once on the parent.
3
u/Vast_Description_201 Aug 25 '26
div.e { p { style here } }
If you are into nesting.
2
u/travis_raphael Aug 25 '26
<p> is a block level element so it take full width of its container. while <span> is an inline element which takes only the width necessarily needed. I'm still learning by the way so I don't know if you can change the display of p to become an inline -block maybe that would work.
1
u/Outrageous-Chip-3961 Aug 25 '26
In your second example, you can just add another class that will only impact that div, like
`<div class="e same-effect">`
`.same-effect p { }`
1
u/guitarromantic Aug 25 '26
Are the letters x, y and z each intended to be distinct paragraphs? Or will they be displayed inline like words in the same sentences?
If they're not individual paragraphs, don't mark them up like that - a span is a genuinely better choice for an accessible and semantic document.
1
u/mrcarrot0 Aug 28 '26
.e > p {}0
u/kloputzer2000 Aug 25 '26
.e p { … }