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

如何固定:before伪元素水平尺寸并实现右对齐?

实现li:before伪元素内容右对齐(动态内容适配)

需求是为ul的li标签添加:before伪元素,每个伪元素内容不同,要求伪元素内容右对齐,且不能使用list-style-type、不能设置统一宽度,伪元素内容为动态生成的行数标识(如rows: 1、rows: 1111等)。

解决方案

通过CSS Grid布局实现动态宽度的右对齐效果,无需固定宽度,自动适配伪元素内容长度:

li {
    list-style-type: none;
    /* 使用Grid布局,分为两列:第一列适配伪元素宽度,第二列占剩余空间 */
    display: grid;
    grid-template-columns: auto 1fr;
    /* 两列之间留间距 */
    column-gap: 8px;
}

li:before {
    color: white;
    content: attr(c);
    /* 伪元素内容右对齐 */
    text-align: right;
}

.red:before { background: red; }
.orange:before { background: orange; }
.blue:before { background: blue; }
.green:before { background: green; }
<ul>
  <li class="red">First</li>
  <li class="orange">Second</li>
  <li class="blue">Third</li>
  <li class="green">Fourth</li>
</ul>
var rows = document.getElementsByTagName('li');
for(var i=0;i<rows.length;i++)
  rows[i].setAttribute("c", "rows: "+"1".repeat(Math.random()*10|0))

效果说明

  • Grid布局让伪元素所在列自动适配内容宽度,无需手动设置固定值
  • text-align: right确保伪元素内容在列内右对齐,实现不同长度内容的右侧对齐效果
  • 列间距column-gap控制伪元素与li文本之间的距离,可按需调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:05:25