英文:
Why background-color is not working on heading and lists inside span?
问题
第二个span
中的内容应用了背景颜色,但第一个span
中包含标题和列表的内容没有应用背景颜色。
颜色样式同时应用在第一个和第二个span
上。
为什么呢?
英文:
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?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
span {
background-color: aqua;
color: red;
}
<!-- language: lang-html -->
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>
<!-- end snippet -->
答案1
得分: 1
我认为问题的一部分在于,对于span元素来说,拥有某些类型的子元素在语义上并不完全正确。正如其他人所指出的,最佳解决方案可能是将<span>替换为<div>,或者类似适当的标签。然而,如果这不可行或不可取,你可以实施一些解决方法:
首先,我认为问题在于span元素的'background-color'样式规则并没有被其子元素继承(Mozilla文档对于哪些样式会默认继承,哪些不会有一个很好的描述在这里)。
你可以通过强制使'background-color'被span的子元素继承来解决这个问题:
span {
background-color: aqua;
color: red;
}
span * {
background-color: inherit;
}
或者通过使用CSS子选择器明确地定位span的子元素:
span, span > * {
background-color: aqua;
color: red;
}
再次强调,用新的span标签替换可能是更好/更简单的解决方案,但上述方法在紧急情况下应该也能起作用。
希望对你有所帮助!
英文:
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!
答案2
得分: 0
Use <div>
不要使用 span 作为第一个。
英文:
Use <div>
not span for the first one
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论