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

如何让列表行右侧按钮居右且垂直居中(不使用Flex)

问题描述

我拥有一个文本列表,每行右侧都配有一个按钮。当某行包含大量文本时,按钮无法实现垂直居中,请问如何让按钮保持居右的同时实现垂直居中?提前感谢!

以下是我的代码:

CSS 代码

ol > li.row {
   position: relative;
   list-style: none;
   border: 1px solid #ccc;
   border-bottom-color: #ccc;
}

.right-side {
   position: absolute;
   top: 0;
   right: 0;
   padding: 15px;   
 }

HTML 代码

<ol>
    <li class="row">
        <h3>Text 1</h3>
        <div class="right-side">
            <button>button 1</button>
        </div>
    </li>
    <li class="row">
        <h3>Text 2</h3>
        <div class="right-side">
            <button>button 2</button>
        </div>
        <p>This is some random text</p>
    </li>
    <li class="row">
        <h3>Text 3</h3>
        <div class="right-side">
            <button>button 3</button>
        </div>
    </li>
    <li class="row">
        <h3>Text 4</h3>
        <div class="right-side">
            <button>button 4</button>
        </div>
        <p>This is another random text</p>
        <p>abc</p>
    </li>
    <li class="row">
        <h3>Text 5</h3>
        <div class="right-side">
            <button>button 5</button>
        </div>
        <p>efg</p>
        <p>random text</p>
        <p>This is another paragraph</p>
    </li>
</ol>

注: 我更倾向于不使用Flex。

预期效果示意图:
预期效果示意图

解决方案

不需要使用Flex,只需修改CSS代码即可实现需求:

ol > li.row {
   position: relative;
   list-style: none;
   border: 1px solid #ccc;
   border-bottom-color: #ccc;
   /* 添加右侧内边距,避免文本被按钮遮挡 */
   padding-right: 100px;
}

.right-side {
   position: absolute;
   top: 50%;
   right: 0;
   padding: 15px;
   /* 通过 translateY 让元素自身垂直居中 */
   transform: translateY(-50%);
 }

原理说明

  • top: 50% 将.right-side元素的顶部定位到父元素(li)垂直方向的中点;
  • transform: translateY(-50%) 将元素自身向上移动其高度的一半,实现整体垂直居中;
  • 给li添加padding-right是为了避免左侧文本过长时被右侧按钮覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:23:25