skip to Main Content

Background-color is applied on the content written in second span but not on first span having headings and list.
color is applied on both first and second span.

Why?

span {
  background-color: aqua;
  color: red;
}
1:

<span>
    <h2>Pointers for block</h2>
    <ol>
        <li>Width of a block level element is 100% of the viewport width.</li>
        <li>Height of a block isn't set by default.</li>
        <li>Height and width can be explicitly set using CSS.</li>
    </ol>
    <h2>Pointers for inline</h2>
    <ol>
        <li>Width of an inline level element is dependent on the content.</li>
        <li>Height of an inline isn't set by default.</li>
        <li>Height and width can't be explicitly set using CSS</li>
    </ol>
</span> 2:

<span>Hello</span>

2

Answers


  1. I think part of the issue is that it is not 100% semantically correct for span elements to have certain types of children. As others have pointed out, the optimal solution probably is to replace <span> with <div>, or a similarly appropriate tag. However, if this is not possible or desirable, there are a few work-arounds you could implement:

    First, I believe the issue is that the span’s ‘background-color’ style rule is not being inherited by its children (the Mozilla docs have a good description of how some styles are inherited by default and others aren’t HERE).

    You can work around this either by enforcing ‘background-color’ to be inherited by the span’s children:

      span {
        background-color: aqua;
        color: red;
      }
    
      span * {
        background-color: inherit;
      }
    

    Or by explicitly targeting the span’s children using the CSS child selector:

      span, span > * {
        background-color: aqua;
        color: red;
      }
    

    Again, replacing your span tags is probably going to be the better / simpler solution, but the above should work in a pinch.

    I hope that helps!

    Login or Signup to reply.
  2. Use <div> not span for the first one

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search