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

WordPress中如何用CSS在H2文本前添加红色空白区块

解决WordPress H2标题样式修改需求

直接给你能实现需求的CSS代码,同时解释关键修正点:

h2 {
    /* 移除原有绿色背景 */
    background-color: transparent !important;
    border-top: 1px solid #01c4c4 !important;
    padding: 6px;
    /* 让标题内部元素垂直居中对齐 */
    display: flex;
    align-items: center;
}

h2::before {
    /* 伪元素必须设置content,哪怕是空值 */
    content: "";
    /* 设置红色区块的尺寸 */
    width: 20px;
    height: 20px;
    /* 红色背景 */
    background-color: #ff6b26;
    /* 和标题文本保持间距 */
    margin-right: 10px;
}

关键修正说明:

  • 你之前的before写法错误,CSS伪元素需要用双冒号::before(单冒号是旧写法,双冒号更规范),并且必须设置content属性,哪怕是空字符串,否则伪元素不会显示。
  • 用background-color: transparent彻底移除原有绿色背景,避免和原有!important优先级冲突。
  • 如果你不想用flex布局,也可以给伪元素加display: inline-block和vertical-align: middle来实现垂直居中,代码如下:
    h2 {
        background-color: transparent !important;
        border-top: 1px solid #01c4c4 !important;
        padding: 6px;
    }
    
    h2::before {
        content: "";
        width: 20px;
        height: 20px;
        background-color: #ff6b26;
        margin-right: 10px;
        display: inline-block;
        vertical-align: middle;
    }
    
  • 可以自行调整width、height和margin-right的值,控制红色区块的大小和与文本的间距。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 12:17:08