为何按钮内文本仍有下划线?CSS样式未生效问题咨询
解决按钮内文本下划线问题
你的问题核心是:text-decoration: none 是给按钮(.button)设置的,但下划线来自按钮内部的 <a> 标签——a标签默认自带下划线样式,父元素的这个样式无法覆盖它的默认属性。
给你两种可行的解决方法:
方法1:给按钮内的a标签单独设置样式
修改CSS,新增针对.button内部a标签的样式,直接移除下划线,同时优化点击区域和文字居中效果:
.button { width:100px; height:100px; border-radius:12px; font-family: arial; color: black; font-size:15px; background-color:red; border: none; /* 替换原有的四个透明边框写法,更简洁 */ position:relative; top:10px; padding: 0; /* 去掉按钮默认内边距,让a标签填满按钮 */ } .button a { text-decoration: none; /* 移除a标签的下划线 */ color: inherit; /* 继承按钮的文字颜色 */ display: block; /* 让a标签铺满整个按钮,扩大点击区域 */ width: 100%; height: 100%; line-height: 100px; /* 让文字垂直居中 */ }
同时修正HTML里的a标签href属性(规范写法需要加引号):
<button class="button"><a href="https://www.youtube.com">This is a button to youtube</a></button>
方法2:调整HTML结构(更推荐)
直接把<a>标签设置为按钮样式(避免button嵌套a的语义问题,HTML规范不允许块级按钮嵌套内联链接):
<a href="https://www.youtube.com" class="button">This is a button to youtube</a>
对应的CSS调整后,text-decoration: none会直接作用在a标签上,下划线自然消失:
.button { display: inline-block; /* 让a标签支持设置宽高 */ width:100px; height:100px; border-radius:12px; font-family: arial; color: black; font-size:15px; text-decoration: none; background-color:red; border: none; position:relative; top:10px; line-height: 100px; /* 垂直居中文字 */ text-align: center; /* 水平居中文字 */ }
内容的提问来源于stack exchange,提问作者Optic Power
相关产品推荐
相关产品推荐

