如何实现全宽按钮文本居中、图标及深色背景固定居右?
解决全宽按钮文本居中、图标固定右侧的问题
要实现文本始终居中、图标及深色背景固定在右侧的效果,只需调整现有CSS的flex布局属性即可,修改后的代码如下:
修改后的CSS代码
.button { display: flex; height: 50px; padding: 0; background: #1e3c72; border: none; outline: none; border-radius: 5px; overflow: hidden; font-family: "Quicksand", sans-serif; font-size: 16px; font-weight: 500; cursor: pointer; width: 100%; /* 让子元素在水平方向居中,垂直方向也居中 */ justify-content: center; align-items: center; } .button:hover { background: #234583; } .button:active { background: #234583; } .button__text, .button__icon { display: inline-flex; align-items: center; padding: 0 24px; color: #fff; height: 100%; } .button__icon { font-size: 1.5em; background: rgba(0, 0, 0, 0.08); /* 利用自动margin把图标推到最右侧 */ margin-left: auto; }
关键修改说明
- 给
.button添加justify-content: center,让按钮内的文本默认在水平方向居中;align-items: center确保元素垂直方向居中。 - 给
.button__icon添加margin-left: auto,借助flex布局的自动margin特性,将图标挤压到按钮最右侧,实现固定位置的效果。 - 移除所有
float: right属性,flex布局下float属性不生效,属于冗余代码。
内容的提问来源于stack exchange,提问作者Twanofzo
相关产品推荐
相关产品推荐

