插件窝 干货文章 如何用CSS高效绘制带背景色的自定义数字样式?

如何用CSS高效绘制带背景色的自定义数字样式?

counter Custom 样式 计数器 529    来源:    2025-03-24

要用CSS高效绘制带背景色的自定义数字样式,你可以使用伪元素和CSS计数器来实现。以下是一个示例代码,展示了如何创建一个带背景色的自定义数字样式:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Number Style</title>
    <style>
        /* 重置列表样式 */
        ol.custom-numbers {
            list-style: none;
            counter-reset: custom-counter;
            padding-left: 0;
        }

        /* 列表项样式 */
        ol.custom-numbers li {
            counter-increment: custom-counter;
            margin-bottom: 10px;
            position: relative;
            padding-left: 40px;
        }

        /* 自定义数字样式 */
        ol.custom-numbers li::before {
            content: counter(custom-counter);
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 30px;
            height: 30px;
            background-color: #007bff;
            color: white;
            border-radius: 50%;
            text-align: center;
            line-height: 30px;
            font-size: 16px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <ol class="custom-numbers">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ol>
</body>
</html>

解释:

  1. counter-reset: custom-counter;:初始化一个名为 custom-counter 的计数器。
  2. counter-increment: custom-counter;:在每个列表项中递增计数器。
  3. li::before:使用伪元素 ::before 来显示计数器的值,并应用自定义样式。
  4. content: counter(custom-counter);:将计数器的值插入到伪元素中。
  5. background-color: #007bff;:设置背景颜色。
  6. border-radius: 50%;:将背景形状设置为圆形。
  7. text-align: center;line-height: 30px;:确保数字在圆形背景中居中显示。

优点:

  • 高效:使用CSS计数器和伪元素,避免了额外的HTML标记。
  • 灵活:可以通过调整CSS样式轻松更改数字的外观(如颜色、大小、形状等)。
  • 可维护:样式与内容分离,便于维护和更新。

这种方法适用于需要自定义数字样式的有序列表,并且可以轻松扩展到其他类似的场景。