为何span内的标题与列表无法应用background-color样式?
问题现象
第二个仅包含文本的<span>元素上,background-color样式正常生效;但第一个包含<h2>标题与<ol>列表的<span>元素上,该样式无法生效,仅color样式在两个<span>上都能正常应用。
相关代码如下:
CSS代码
span { background-color: aqua; color: red; }
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>
原因分析
<span>是内联元素,根据HTML规范,内联元素不能嵌套块级元素(<h2>、<ol>都属于块级元素)。浏览器遇到这种不符合规范的嵌套时,会自动修正DOM结构:把块级元素从<span>中剥离出来,最终<span>实际只包裹了块级元素之间的空白内容,所以看不到背景色;而color样式会被块级元素继承,因此所有文字都显示红色。
解决方案
有两种可行的解决方法:
- 把第一个
<span>替换成块级元素,比如<div>,这是最符合规范的做法 - 给第一个
<span>设置CSS属性display: block或display: inline-block,让它变成块级/行内块级元素,从而能正确包裹内部的块级内容
修改后的代码示例:
方法1:替换为div
1: <div> <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> </div> 2: <span>Hello</span>
方法2:修改span的display属性
span { background-color: aqua; color: red; } span.wrap-block { display: block; }
1: <span class="wrap-block"> <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>
内容的提问来源于stack exchange,提问作者user22173557
相关产品推荐
相关产品推荐

