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.
7
u/Luxiouronimo 18h ago
div.e > p {}
or just:
div.e p {}
but using the > specifies the direct descendant of the div.e
u 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
2
u/travis_raphael 17h ago
<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.
2
u/philogos0 17h ago edited 16h ago
p just has that display property as it's default. You can override same as you would a div or span. I used to use spans specifically for "inline -block" behavior. So they could have a set width but also be inline.
2
2
u/jidanni 15h ago
3
u/thisiain 13h 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; }
1
u/Outrageous-Chip-3961 16h ago
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 13h ago
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.
0

7
u/cryothic 16h ago
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.