如何用CSS实现H1标题下方的酒红色矩形装饰效果?
实现H1标题下方的酒红色矩形装饰
你当前用background-image: linear-gradient()的方法虽能做出类似效果,但存在装饰条尺寸/位置难精准控制、标题换行时装饰条重复出现的问题。下面提供几种更可靠的实现方案:
方案1:伪元素实现(推荐)
通过伪元素可以精准控制装饰条的各项属性,且不干扰原标题布局:
h1 { font-size: 48px; color: #16343E; font-family: 'Roboto', sans-serif; font-weight: 900; position: relative; display: inline-block; /* 让装饰条宽度匹配标题内容 */ } h1::after { content: ''; position: absolute; bottom: 6px; /* 调整装饰条与文字的间距 */ left: 0; width: 100%; height: 7px; /* 装饰条的高度 */ background-color: #863034; }
<h1>Welcome</h1>
优势:
- 可通过
height和bottom精准调整装饰条的高度与位置 - 标题换行时(若设为块级元素),装饰条会保持在整体标题底部
- 不影响文字本身的背景样式
方案2:border-bottom快速实现
如果装饰条刚好贴合文字底部,用边框实现最简洁:
h1 { font-size: 48px; color: #16343E; font-family: 'Roboto', sans-serif; font-weight: 900; display: inline-block; border-bottom: 7px solid #863034; padding-bottom: 3px; /* 调整文字与边框的间距 */ }
<h1>Welcome</h1>
方案3:优化你的渐变方法
若想保留渐变思路,可调整参数让装饰条更规整:
h1 { font-size: 48px; color: #16343E; font-family: 'Roboto', sans-serif; font-weight: 900; display: inline; background-image: linear-gradient(to bottom, transparent 60%, #863034 60%); background-repeat: no-repeat; background-size: 100% 7px; /* 第二个值控制装饰条高度 */ background-position: 0 92%; /* 控制装饰条垂直位置 */ }
用transparent替代白色,避免与页面背景冲突,同时通过background-size和background-position精准控制装饰条的大小与位置。
内容的提问来源于stack exchange,提问作者SkyT
相关产品推荐
相关产品推荐

