使用Styled Components实现鼠标悬停下划线效果失效问题
解决Styled Components中hover下划线不生效的问题
你的代码里有两个核心问题导致下划线无法正常显示:
1. 定位上下文缺失
::after伪元素使用了position: absolute,但父元素li默认是静态定位(position: static),这会让伪元素相对于页面根元素(body)定位,而非目标li元素,所以你看不到它。给li添加position: relative,就能让伪元素相对于li进行定位。
2. 可选优化:添加过渡效果
直接从width: 0切换到width: 100%会很生硬,加上过渡属性可以让下划线平滑展开,提升交互体验。
另外注意:代码里的&是HTML转义字符,实际在Styled Components中要写成&才能正确识别伪元素和hover状态。
修正后的代码
export const Links = styled.div` ul { display: flex; } li { color: #fff; text-decoration: none; list-style-type: none; margin: 1.4vh; cursor: pointer; letter-spacing: 0.1rem; position: relative; /* 添加定位上下文 */ &::after { content: ""; width: 0; height: 4px; background-color: #ff914d; position: absolute; bottom: 0; left: 0; transition: width 0.3s ease; /* 平滑过渡宽度变化 */ } &:hover::after { width: 100%; } } `;
如果下划线和文字距离过近,可以调整bottom的值(比如改成-2px)来拉开间距。
内容的提问来源于stack exchange,提问作者Routfin
相关产品推荐
相关产品推荐

