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

如何在保留float:right按钮布局的同时实现文本垂直居中?

问题

我有一个包含信息文本的div,其中的取消按钮通过float属性定位在右侧。我希望将信息文本垂直居中,但尝试的方法都无效。如何在保持按钮高度和位置不变的前提下,实现文本的垂直居中?

代码示例

CSS

.scb-frmo-frbtn {
  width: 75%;
  border-top: 1px solid var(--c1) !important;
  padding-top: 8px;
  padding-left: 5px;
  padding-bottom: 8px;
  box-sizing: border-box;
  font-family: var(--dm);
  cursor: pointer;
  transition: .1s;
  overflow: hidden;
  border-radius: 0;
  border: none;
  height: 57px;
}

.scb-frmo-frbtn > .title {
  font-weight: 800;
  font-size: 18.5px;
  color: var(--c5);
  vertical-align: middle;
}

.scb-frmo-frbtn > .desc {
  font-weight: lighter;
  margin-left: 10px;
  vertical-align: middle;
  color: lightgray;
  font-size: 13px;
}

.scb-frmo-frbtn > button.cancel-fr {
  float: right;
  background-color: var(--c6);
  color: white;
  font-weight: normal;
  margin-right: 8px;
  cursor: pointer;
  border-radius: 100%;
  border: 1px solid var(--c6);
  height: 40px;
  width: 40px;
  transition: .1s;
}

HTML

<div class="scb-frmo-frbtn">
  <span class="title">username</span>
  <span class="desc">Outgoing Friend Request</span>
  <button class="cancel-fr">X</button>
</div>

当前效果

当前效果

解决方案

可以通过Flex布局实现文本垂直居中,同时保留按钮原有尺寸和位置,具体修改如下:

修改后的CSS

.scb-frmo-frbtn {
  width: 75%;
  border-top: 1px solid var(--c1) !important;
  padding-left: 5px;
  padding-right: 8px;
  box-sizing: border-box;
  font-family: var(--dm);
  cursor: pointer;
  transition: .1s;
  overflow: hidden;
  border-radius: 0;
  border: none;
  height: 57px;
  display: flex;
  align-items: center;
}

.scb-frmo-frbtn > .title {
  font-weight: 800;
  font-size: 18.5px;
  color: var(--c5);
}

.scb-frmo-frbtn > .desc {
  font-weight: lighter;
  margin-left: 10px;
  color: lightgray;
  font-size: 13px;
}

.scb-frmo-frbtn > button.cancel-fr {
  margin-left: auto;
  background-color: var(--c6);
  color: white;
  font-weight: normal;
  cursor: pointer;
  border-radius: 100%;
  border: 1px solid var(--c6);
  height: 40px;
  width: 40px;
  transition: .1s;
}

说明

  1. 给父容器scb-frmo-frbtn添加display: flex和align-items: center,让所有子元素自动垂直居中,同时保留容器固定高度。
  2. 移除按钮的float: right,改用margin-left: auto实现靠右对齐,效果和原float一致且兼容Flex布局。
  3. 移除文本元素的vertical-align: middle,Flex布局已实现垂直居中,该属性不再需要。
  4. 将按钮的margin-right: 8px移到父容器的padding-right: 8px,避免按钮出现溢出问题。

修改后文本会垂直居中,按钮的高度和位置完全保持不变。

内容的提问来源于stack exchange,提问作者ghosty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:46:34