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

如何将h2元素的font-weight设为normal?尝试通过父元素实现

解决H2字体粗细无法通过父元素修改的问题

你尝试通过父元素设置font-weight: normal来改变h2的字体粗细但未生效,核心原因是:浏览器默认给h2标签设置了font-weight: bold的直接样式,这个样式的优先级高于从父元素继承来的样式,所以父元素的设置无法覆盖h2自身的默认样式。

以下是几种可行的解决方案:

方案1:直接给h2设置样式

这是最直接高效的方式,直接覆盖h2的默认字体粗细:

h2 {
  margin: 0;
  padding: 0;
  font-weight: normal; /* 添加这行覆盖默认样式 */
}
.top, .date {
  display: inline-block;
  width: 150px;
  height: 30px;
  border: 2px solid black;
  text-align: center;
}
.date {
  float: right;
  font-size: 16px; 
}

方案2:通过父类选择器精准控制h2

如果只想让特定父元素下的h2字体变细,可使用父类与h2的组合选择器:

h2 {
  margin: 0;
  padding: 0;
}
.top, .date {
  display: inline-block;
  width: 150px;
  height: 30px;
  border: 2px solid black;
  text-align: center;
}
.date {
  float: right;
  font-size: 16px; 
}
/* 仅让.date类父元素下的h2字体变细 */
.date h2 {
  font-weight: normal;
}
/* 若需要所有.top类父元素下的h2变细,可添加这行 */
/* .top h2 { font-weight: normal; } */

方案3:使用CSS变量实现灵活控制

通过父元素定义CSS变量,让h2读取变量值,后续修改父元素的变量即可快速调整h2样式:

h2 {
  margin: 0;
  padding: 0;
  font-weight: var(--h2-weight, bold); /* 默认保持加粗,可被父元素变量覆盖 */
}
.top, .date {
  display: inline-block;
  width: 150px;
  height: 30px;
  border: 2px solid black;
  text-align: center;
}
.date {
  float: right;
  font-size: 16px; 
  --h2-weight: normal; /* 父元素定义变量,h2自动继承使用 */
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:50:49