如何防止将div替换为button后按钮尺寸缩小?
问题
设置了宽高47px的.box样式,应用在<div>上显示正常,但替换为<button>后,按钮尺寸明显小于div,需要让按钮与div尺寸完全一致。
代码示例
CSS
.box { position: relative; background: red; width: 47px; height: 47px; border-radius: 4px; border-width: 4px; border-style: solid; border-top-color: rgba(255, 255, 255, 0.5); border-left-color: rgba(0, 0, 0, 0.3); border-right-color: rgba(0, 0, 0, 0.3); border-bottom-color: rgba(0, 0, 0, 0.8); } .box.box2 { background: red; }
HTML
<button class="box box2" type="button"></button> <button class="box" type="button"></button> <div class="box"></div>
解决方案
问题根源在于<button>元素带有浏览器默认的内边距,且部分浏览器中按钮的盒模型与<div>不一致,导致尺寸计算偏差。只需在.box样式中添加两行代码即可修复:
.box { /* 原有样式保留 */ box-sizing: border-box; /* 统一盒模型,宽高包含边框和内边距 */ padding: 0; /* 清除按钮默认内边距 */ }
修复后完整代码
CSS
.box { position: relative; background: red; width: 47px; height: 47px; border-radius: 4px; border-width: 4px; border-style: solid; border-top-color: rgba(255, 255, 255, 0.5); border-left-color: rgba(0, 0, 0, 0.3); border-right-color: rgba(0, 0, 0, 0.3); border-bottom-color: rgba(0, 0, 0, 0.8); box-sizing: border-box; padding: 0; } .box.box2 { background: red; }
HTML
<button class="box box2" type="button"></button> <button class="box" type="button"></button> <div class="box"></div>
内容的提问来源于stack exchange,提问作者user17631451
相关产品推荐
相关产品推荐

