如何让元素自动继承容器内边距?按钮右侧黑框自适应实现问询
问题:让按钮右侧箭头的黑色框自动适配容器空间
我想要制作的按钮默认样式:
hover状态样式:
目前在桌面端通过以下代码实现了预期效果,但需要手动设置padding,且缩放适配移动端时效果不佳(移动端适配问题:
)。由于屏幕尺寸多样,希望能让按钮右侧箭头的黑色框自动填充容器的可用空间。
当前实现代码
CSS代码
.white-button-arrow { width: 70%; height: 75px; font-size: 16px; border-radius: 10px; border: solid 3px #000000; cursor: pointer; position: relative; background: white; display: flex; justify-content: space-between; align-items: center; padding: 0; transition: all 0.3s ease; } .white-button-arrow-text { padding-left: 10px; font-family: Friends-UltraBold !important; font-size: 200%; } .white-button-arrow-icon { font-size: 200%; position: relative; border-left: 1px solid #ffffff29; border-radius: 0 10px 10px 0; padding: 20px 20px 22px 20px; background: #000000; color: #fff; transition: all 0.3s ease; transform-origin: right; } .white-button-arrow:hover .white-button-arrow-icon { color: #ff5a45; padding-left: 10%; text-indent: -60%; } .white-button-arrow:hover { background: #ff5a45; }
HTML代码
<div> <a target="_blank" rel="noopener"> <button class="white-button-arrow" style="width: 100%; translate: 0px 200px;"> <span class="white-button-arrow-text"><b>GOOGLE-MAPS</b></span> <span class="white-button-arrow-icon" style="font-family:"> > </span> </button> </a> </div>
优化方案
核心思路是利用flex布局特性,让箭头框自动填满按钮高度,通过flex分配空间避免手动设置padding,适配不同屏幕尺寸。
修改后的CSS代码
.white-button-arrow { width: 70%; min-height: 75px; /* 用min-height保证最小高度,适配移动端内容 */ font-size: 16px; border-radius: 10px; border: solid 3px #000; cursor: pointer; background: white; display: flex; align-items: stretch; /* 让子元素自动拉伸填满按钮高度 */ padding: 0; transition: all 0.3s ease; } .white-button-arrow-text { padding: 0 10px; /* 仅设置左右内边距,上下随按钮高度自动适配 */ font-family: Friends-UltraBold !important; font-size: 200%; display: flex; align-items: center; /* 文本垂直居中 */ flex: 1; /* 文本区域占据按钮剩余空间,箭头框固定在右侧 */ } .white-button-arrow-icon { font-size: 200%; border-left: 1px solid #ffffff29; border-radius: 0 10px 10px 0; background: #000; color: #fff; transition: all 0.3s ease; display: flex; align-items: center; justify-content: center; /* 箭头在黑色框内居中 */ padding: 0 20px; /* 仅设置左右内边距,高度自动填满按钮 */ transform-origin: right; } .white-button-arrow:hover .white-button-arrow-icon { color: #ff5a45; padding-left: 30px; /* 改用固定值调整箭头位置,避免小屏幕上的百分比偏移异常 */ padding-right: 10px; } .white-button-arrow:hover { background: #ff5a45; }
修改后的HTML代码
<div> <a target="_blank" rel="noopener"> <button class="white-button-arrow"> <span class="white-button-arrow-text"><b>GOOGLE-MAPS</b></span> <span class="white-button-arrow-icon"> > </span> </button> </a> </div>
优化说明
- 按钮使用
align-items: stretch,让箭头框自动填满按钮高度,无需手动设置上下padding - 文本区域通过
flex:1占据剩余空间,确保箭头框始终固定在按钮右侧 - 将固定
height改为min-height,适配移动端不同内容高度需求 - hover状态的箭头位置调整改用固定padding值,避免百分比在小屏幕上的偏移异常
内容的提问来源于stack exchange,提问作者Phong2902
相关产品推荐
相关产品推荐

