如何使用类似于SASS的darken()的CSS变量创建阴影? [英] How to create color shades using CSS variables similar to darken() of SASS?

查看:355
本文介绍了如何使用类似于SASS的darken()的CSS变量创建阴影?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种修改CSS变量的方法,就像在SCSS中一样

I'm looking a way of modifying a CSS variable as you would in SCSS

定义像主色这样的颜色,然后自动获得焦点和活动状态的阴影. 基本上,想要更改css变量中的一个变量,并获得3种相同颜色的阴影.

Define a color like primary - and automatically I would get shades for focus and actives states. Basically, would like to change one variable in css variables and get 3 shades of the same color.

我想在CSS中实现什么

What Id like to achieve in CSS

$color-primary: #f00;

.button {
    background: $color-primary;

    &:hover,
    &:focus {
        background: darken($color-primary, 5%);
    }

    &:active {
        background: darken($color-primary, 10%);
    }
}

试图实现:

:root {
    --color-primary: #f00;
    --color-primary-darker: #f20000  //     var(--color-primary) * 5% darker
    --color-primary-darkest: #e50000 //     var(--color-primary) * 10% darker
}

.button {
    background: var(--color-primary);
}

.button:hover,
.button:focus {
    background: var(--color-primary-darker);
}

.button:active {
    background: var(--color-primary-darkest);
}

推荐答案

您可以考虑 hsl() 颜色,只需控制亮度:

You can consider hsl() colors and simply control the lightness:

:root {
    --color:0, 100%; /*the base color*/
    --l:50%; /*the initial lightness*/
    
    --color-primary: hsl(var(--color),var(--l));
    --color-primary-darker: hsl(var(--color),calc(var(--l) - 5%));
    --color-primary-darkest: hsl(var(--color),calc(var(--l) - 10%)); 
}

.button {
    background: var(--color-primary);
    display:inline-block;
    padding:10px 20px;
    color:#fff;
    cursor:pointer;
}

.button:hover,
.button:focus {
    background: var(--color-primary-darker);
}

.button:active {
    background: var(--color-primary-darkest);
}

<span class="button">some text</span>

作为旁注, darken() 也正在做同样的事情:

As a side note, darken() is also doing the same thing:

使颜色变深.接受一种颜色和一个介于0%和100%之间的数字,然后返回一种颜色,该颜色的亮度降低减少了该数量.

这篇关于如何使用类似于SASS的darken()的CSS变量创建阴影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆