You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS通配符*优先级异常高于header标签问题求助

解决*选择器导致header样式被覆盖的问题

问题根源

不是选择器优先级比header高,而是你用给所有元素(包括header里的nav、a、ul、div这些子元素)都加了深色背景,这些子元素的背景会把header的浅蓝背景完全挡住,看起来就像header的样式没生效。

z-index管的是元素层叠顺序,和背景色显示没关系;加id、!important只能提升header本身的优先级,但子元素的背景还是会盖在它上面,所以没用。

两种解决方案

方案1:改用body设置全局样式(推荐)

不要用*设置背景色,把全局样式移到body上,其他元素默认背景透明,不会遮挡header:

@charset "utf-8";
@import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@1,500&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Encode+Sans:wght@500&display=swap");

/* 全局样式写在body上,取代*选择器 */
body {
    color: rgba(255,255,255,0.5);
    background-color: rgba(36,37,42,1);
    margin: 0; /* 去掉body默认外边距,避免header顶部留白 */
}

header{
    background-color: aquamarine;
    min-height: 80px;
    top: 0;
    padding: 0;
    position: sticky;
    display: flex;
    justify-content: flex-end;
    z-index: 1000;
 }

.navbar {
    font-family: "Montserrat", sans-serif;
    font-weight: 500;
    font-size: 1em;
    width: 100%;
    height: 20%;
    padding-bottom: 0;
    position: sticky;
    top: 0;
}

.main-nav{
    float: right;
}

.logo img {
    height: auto;
    width: 12%;
    padding: 0.5%;
}

/* 顺便修复导航的默认样式,让它横向排列 */
.main-nav ul {
    list-style: none;
    margin: 0;
    padding: 25px 10px;
}

.main-nav li {
    display: inline-block;
    margin: 0 15px;
}

.main-nav a {
    text-decoration: none; /* 去掉链接下划线 */
}

方案2:重置header子元素的背景色

如果你一定要保留*选择器,就给header内部所有子元素设置背景透明,让header的背景透出来:

@charset "utf-8";
@import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@1,500&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap");
@import url("https://fonts.googleapis.com/css2?family=Encode+Sans:wght@500&display=swap");

* {
    color: rgba(255,255,255,0.5);
    background-color: rgba(36,37,42,1);
}

header,
header *,
.navbar,
.navbar *,
.main-nav,
.main-nav * {
    background-color: transparent;
}

header{
    background-color: aquamarine;
    min-height: 80px;
    top: 0;
    padding: 0;
    position: sticky;
    display: flex;
    justify-content: flex-end;
    z-index: 1000;
 }

/* 其他样式不变 */
.navbar {
    font-family: "Montserrat", sans-serif;
    font-weight: 500;
    font-size: 1em;
    width: 100%;
    height: 20%;
    padding-bottom: 0;
    position: sticky;
    top: 0;
}

.main-nav{
    float: right;
}

.logo img {
    height: auto;
    width: 12%;
    padding: 0.5%;
}

效果说明

两种方案都能让header的浅蓝背景正常显示,方案1更规范,不会影响其他元素的默认样式,推荐使用。

内容的提问来源于stack exchange,提问作者Muhammad5777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:11:09