如何去除被<a>标签包裹的按钮文本下方的下划线?
按钮被<a>标签包裹后,文本下方出现蓝色下划线,即使给按钮元素及其伪类设置text-decoration: none也无效。

你提供的代码:
CSS代码:
#p { position: relative; top: 10px; display: block; margin-left: auto; margin-right: auto; height: 100px; width: 55%; font-size: 30px; font-family: 'Bitter', serif; color: #588b42; border: none; background-color: #1a1a19; } #p:hover, #p:visited, #p:link, #p:active { text-decoration: none; }
HTML代码:
<a href="portfolio.html" target="_blank"><button id="p">Portfolio</button></a>
问题原因:
下划线不是来自按钮元素,而是来自包裹它的<a>标签——浏览器默认会给超链接添加下划线样式,你之前的CSS只针对按钮设置,没作用到<a>上。
解决方案:
直接给包裹按钮的<a>标签设置text-decoration: none,同时覆盖它的所有伪状态:
方案1(使用:has()选择器,需浏览器支持):
a:has(#p), a:has(#p):hover, a:has(#p):visited, a:has(#p):link, a:has(#p):active { text-decoration: none; }
方案2(兼容性更好,给<a>加类名):
修改后的HTML:
<a href="portfolio.html" target="_blank" class="button-link"><button id="p">Portfolio</button></a>
对应的CSS:
.button-link, .button-link:hover, .button-link:visited, .button-link:link, .button-link:active { text-decoration: none; }
这样就能彻底去掉按钮文本的下划线了。
内容的提问来源于stack exchange,提问作者FiGiLU
相关产品推荐
相关产品推荐

