如何实现CSS hover时边框仅延伸至最后一个字母(不含letter-spacing)
问题:Hover状态下底部边框仅延伸至最后一个字母末尾(排除letter-spacing部分)
原CSS代码如下:
.item { font-size: 10px; font-weight: 500; line-height: 25px; letter-spacing: 0.65em; padding-left: -0.65em; text-align: center; text-transform: uppercase; margin: 0 50px -1px 0; font-style: normal; border-bottom: 1px solid #D7D3CE; } .item:hover { border-bottom: 1px solid #000000; }
需求:实现hover时底部边框只覆盖到最后一个字母的末尾,不包含设置的letter-spacing所产生的右侧间距。
解决方案
方案1:使用伪元素模拟底部边框(无需修改HTML结构)
通过::after伪元素替代原生border-bottom,精确控制边框的右侧范围,抵消最后一个字符的letter-spacing:
.item { font-size: 10px; font-weight: 500; line-height: 25px; letter-spacing: 0.65em; padding-left: -0.65em; text-align: center; text-transform: uppercase; margin: 0 50px -1px 0; font-style: normal; position: relative; /* 为伪元素定位提供基准 */ /* 移除原有的border-bottom */ } /* 默认状态的底部边框 */ .item::after { content: ""; position: absolute; bottom: -1px; /* 对齐原有的margin-bottom位置 */ left: 0; right: 0.65em; /* 减去最后一个字符的letter-spacing宽度 */ height: 1px; background-color: #D7D3CE; } /* Hover状态切换边框颜色 */ .item:hover::after { background-color: #000000; }
方案2:通过子元素包裹文本(需调整HTML结构)
给文本添加一个inline-block子元素,用负margin-right抵消最后一个字符的letter-spacing,再给子元素设置边框:
修改后的HTML:
<div class="item"> <span>你的文本内容</span> </div>
对应CSS:
.item { font-size: 10px; font-weight: 500; line-height: 25px; text-align: center; text-transform: uppercase; margin: 0 50px -1px 0; font-style: normal; } .item span { letter-spacing: 0.65em; padding-left: -0.65em; display: inline-block; margin-right: -0.65em; /* 抵消最后一个字符的letter-spacing */ border-bottom: 1px solid #D7D3CE; } .item:hover span { border-bottom: 1px solid #000000; }
内容的提问来源于stack exchange,提问作者user1272597
相关产品推荐
相关产品推荐

