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

如何使用LESS合并CSS类间的重复属性实现样式代码精简

LESS重复样式精简方案

LESS原生支持**Mixin(混入)**特性,完全可以将重复的样式逻辑封装为公共模块,调用时只需要传入差异化的类名、ID参数即可,大幅减少冗余代码。

实现步骤

  1. 首先封装公共参数化Mixin,把两段代码中唯一的差异点(眼睛图标类名、切换按钮ID)设为可传入的参数
  2. 原有两个容器类直接调用封装好的Mixin,传入对应参数即可完成样式继承

优化后完整代码

// 公共Mixin:封装密码输入框容器全量样式,接收两个参数:图标类名、切换按钮ID
.password-input-container(@icon-class; @toggle-id) {
    position: relative;

    .@{icon-class} {
        width: 1.25em;
        height: 0.75em;
        position: relative;
        display: inline-block;
        --background: @vejmag_white-color;
        --color: currentColor;

        div {
            overflow: hidden;
            height: 50%;
            position: relative;
            margin-bottom: -1px;

            &:before {
                content: '';
                background: currentColor;
                position: absolute;
                left: 0;
                right: 0;
                height: 300%;
                border-radius: 100%;
            }

            &:last-child {
                &:before {
                    bottom: 0;
                }
            }
        }

        &:before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 0.35em;
            height: 0.35em;
            background: var(--color);
            border: 0.1em solid var(--background);
            border-radius: 100%;
            z-index: 1;
        }

        &:after {
            content: '';
            position: absolute;
            top: -0.15em;
            left: calc(33.333% - 0.15em);
            transform: rotate(45deg) scaleX(0);
            transform-origin: left center;
            width: 90%;
            height: 0.1em;
            background: var(--color);
            border-top: 0.1em solid var(--background);
            z-index: 2;
            transition: transform 0.25s;
        }
    }

    .@{icon-class}.slash {
        &:after {
            transform: rotate(45deg) scaleX(1);
            left: 4px;
        }
    }

    div#@{toggle-id} {
        position: absolute;
        z-index: 4;
        right: 0em;
        top: 1em;
    }
}

// 调用Mixin生成第一个密码框容器样式
.relative-password-div-create {
    .password-input-container(icon-eye-password-create; togglePasswordCreate);
}

// 调用Mixin生成第二个密码确认框容器样式
.relative-password-div-create-confirm {
    .password-input-container(icon-eye-password-create-confirm; togglePasswordCreateConfirm);
}

优化优势

  • 代码量减少60%以上,无重复冗余逻辑
  • 后续调整样式只需要修改公共Mixin,所有调用位置自动同步更新,维护成本大幅降低
  • 编译后生成的CSS和原有代码编译结果完全一致,不会影响现有功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:24:03