Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change color to lighter or darker by percentage CSS

Tags:

css

We have a big application on the site and we have a few links which are, let's say blue color like the blue links on this site. Now I want to make some other links, but with lighter color. Obviously I can just do simply by the hex code adding in the CSS file, but our site lets user decide what colors they want for their customized profile/site (like Twitter).

So, my question is: can we reduce the color by percentage?

Let's say the following code is CSS:

a {   color: blue; }  a.lighter {   color: -50%; // obviously not correct way, but just an idea } 

OR

a.lighter {   color: blue -50%;  // again not correct, but another example of setting color and then reducing it } 

Is there a way to reduce a color by a percentage?

like image 938
Basit Avatar asked Oct 26 '09 16:10

Basit


People also ask

How do I change the color of a percent in CSS?

Approach: We can dynamically change the color of any element by percentage using the filter property in CSS. The brightness() function of the filter property is used to dynamically change color by percentage. The brightness function takes a value in percentage to set the brightness of that color.

How do you darken a color in CSS?

The CSS preprocessors Sass and Less can take any color and darken() or lighten() it by a specific value. But no such ability is built into JavaScript. This function takes colors in hex format (i.e. #F06D06, with or without hash) and lightens or darkens them with a value.

How do you lighten a darken or hex color?

Just pass in a string like "3F6D2A" for the color ( col ) and a base10 integer ( amt ) for the amount to lighten or darken. To darken, pass in a negative number (i.e. -20 ).


1 Answers

You can do this with CSS filters in all modern browsers (see the caniuse compatibility table).

.button {    color: #ff0000;  }    /* note: 100% is baseline so 85% is slightly darker,      20% would be significantly darker */  .button:hover {    filter: brightness(85%);  }
<button class="button">Foo lorem ipsum</button>

Here's more reading from CSS Tricks about the various filters you can use: https://css-tricks.com/almanac/properties/f/filter/

like image 101
imjared Avatar answered Nov 25 '22 10:11

imjared