0

Background

As far as I understand from the internet, SPAN and DIV fulfill pretty much the same basic purpose, namely group a bunch of HTML statements to perform some group actions. SPANs and DIVs should not affect colors.

Question

Can anyone tell me why background colors don't work when DIVs are replaces by SPANs?

Symptoms

In the code below I want the text surrounded by the DIV to have a red background color. Unfortunately it has a white background color. However, if I change the SPAN into a DIV (line number 1), then I get the color I asked for.

<span class="benefits" style="background-color: red;">
     <div>2023 Survey of 10 billion Respondents!</div>
</span>

You can find a live Codepen example here.

What have I tried?

  • Inline CSS
  • External CSS
  • Read about SPANs on MDN
  • Read about DIVs on MDN
  • Read about background-color on MDN
  • Cross-browser testing on Browserling. I tried Windows with several versions of Chrome, several versions of Firefox and Safari
  • Tested with Firefox 110.0.1 64-bit on a Linux machine
  • Tested with Chromium 110.0.5481.100 on a Linux machine
  • Tested with Codepen
  • Search Google.
  • 1
    span is an inline element, make it block and it will work – Temani Afif Mar 26 '23 at 11:54
  • 1
    div elements are **not allowed** inside span elements – Quentin Mar 26 '23 at 11:56
  • besides what has been mentioned by Temani Afif, you should not semantically misuse a span and a div in that context. A span is an inline container and a div is a block-level container. Use the correct container in the first place. Semantically a div inside a span is just wrong. – tacoshy Mar 26 '23 at 11:56
  • @tacoshy — It's structure, not semantics. div and span are generic elements which don't have any semantics. – Quentin Mar 26 '23 at 11:57
  • Should I use DIVs only, or SPANs only, but not mixed together? Is that the issue? – Ballet_Cage Mar 26 '23 at 12:02
  • It depends on what you try to do. Should it be a block then use divs or should it be inline with other text then use a span: However never use a div inside a span. The other way around it would be ok. – tacoshy Mar 26 '23 at 14:41

0 Answers0