You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现全宽按钮文本居中、图标及深色背景固定居右?

解决全宽按钮文本居中、图标固定右侧的问题

要实现文本始终居中、图标及深色背景固定在右侧的效果,只需调整现有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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 07:25:17