CSS样式问题:头部标题文本框未继承header背景色而沿用body背景色
问题描述
开发过程中修改了包含logo和标题的头部header的背景色后,发现标题文字所在的文本框没有应用header的背景色,反而继承了网站body的背景色。
相关代码
CSS代码
* { margin: 0px; padding: 0px; font-family: arial, helvetica, sans-serif; font-size: 12px; background-color: #C0C0C0; } .headerMenu { background-color: #00b9ED; height: 40px; border-bottom: 0px; padding-left: auto; padding-right: auto; padding-bottom: 10px; width: 100%; } #wrapper { margin-left: auto; margin-right: auto; width: 1000px; padding-top: 0px; padding-bottom: 0px; } .logo { width: 125px; } .logo img { background-color: #00b9ED; position: absolute; width: 50px; height: 38px; top: 0; left: 10px; } .headerTitle { background-color: #00b9ED; position: absolute; top: 15px; left: 80PX; font-family: 'oswald', arial, sans-serif; }
HTML代码
<!DOCTYPE HTML> <HTML> <HEAD> <title>FINDPETS</title> <link href="./css/style.css" rel="stylesheet" type="text/css" /> </HEAD> <body> <div class="headerMenu"> <div id="wrapper"> <div class="headerTitle"> <h2>PET FRIENDS</h2> </div> <div class="logo"> <img src="./IMG/dog_bone_logo.png" /> </div> </div> </div> </body> </HTML>
错误效果

解决方案
根因说明
全局通配符*的规则给所有元素统一设置了background-color: #C0C0C0,该规则优先级高于样式继承,因此标题所在的<h2>元素会直接使用灰色背景,无法透出父级.headerMenu的蓝色背景。
方案1:调整全局样式逻辑(推荐)
通配符不适合设置全局背景色,把背景色配置移动到body选择器即可,同时可以删掉子元素冗余的背景色配置,补充父级定位避免绝对定位元素错位:
* { margin: 0px; padding: 0px; font-family: arial, helvetica, sans-serif; font-size: 12px; /* 删除原通配符里的background-color配置 */ } /* 新增body选择器设置页面全局背景 */ body { background-color: #C0C0C0; } .headerMenu { background-color: #00b9ED; height: 40px; border-bottom: 0px; padding-left: auto; padding-right: auto; padding-bottom: 10px; width: 100%; /* 补充相对定位,子元素绝对定位会相对于当前父级,不会错位 */ position: relative; } #wrapper { margin-left: auto; margin-right: auto; width: 1000px; padding-top: 0px; padding-bottom: 0px; } .logo { width: 125px; } .logo img { /* 删掉冗余的background-color配置 */ position: absolute; width: 50px; height: 38px; top: 0; left: 10px; } .headerTitle { /* 删掉冗余的background-color配置 */ position: absolute; top: 15px; left: 80PX; font-family: 'oswald', arial, sans-serif; } /* 补充h2的字体设置,避免被通配符强制改成12px */ .headerTitle h2 { font-size: 20px; }
方案2:局部修改标题样式
如果不想调整全局通配符逻辑,单独给标题元素设置背景透明即可,新增如下CSS规则:
.headerTitle h2 { background-color: transparent; /* 可根据需要调整字号 */ font-size: 20px; }
内容的提问来源于stack exchange,提问作者Alexander Katona
相关产品推荐
相关产品推荐

