如何用HTML和CSS为标题添加底部边框?尝试后未达预期
解决标题底部边框/下划线的预期效果问题
你当前代码存在几个问题,导致无法达到预期效果:
margin-bottom: 30缺少单位,需补充为margin-bottom: 30px(或其他适配的单位)- 同时使用
border-bottom(撑满容器的通栏横线)和text-decoration: underline(跟随文字长度的下划线),两者叠加会干扰最终显示效果
结合你想要的文字下方短横线效果,提供两种常用解决方案:
方案1:保留与文字宽度一致的下划线
去掉多余的border-bottom,调整下划线参数即可:
.widget-title { font-size: 1em; margin-bottom: 30px; text-decoration: underline; text-underline-offset: 0.5rem; text-decoration-thickness: 0.1875rem; text-decoration-color: green; color: black; /* 可选:若标题为块级元素,添加此属性让下划线仅跟随文字宽度 */ display: inline-block; }
<h1 class="widget-title"> Widget title </h1>
方案2:添加比文字短的居中底部横线
如果需要比文字宽度更短的居中横线,用伪元素实现更灵活:
.widget-title { font-size: 1em; margin-bottom: 30px; color: black; position: relative; padding-bottom: 0.5rem; } .widget-title::after { content: ""; position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); width: 60%; /* 可自定义横线宽度 */ height: 0.1875rem; background-color: green; }
<h1 class="widget-title"> Widget title </h1>
内容的提问来源于stack exchange,提问作者Khondokar Shamim Ahmed
相关产品推荐
相关产品推荐

