Background color based border

I often use darken and lighten in SASS styles. I am currently writing a class that will have a border, but will depend on another class for the background color. I want to set the border color of the darken background color of the element.

Something like that:

 .blue { background: #00f; } .red { background: #f00; } .border { border: 2px solid darken(background, 20); } 

Then the markup will be:

 <div id="colored-box" class="blue border"> <p> I have a dark blue border! </p> </div> <div id="colored-box" class="red border"> <p> I have a dark red border! </p> </div> 

Naturally, if this worked, since I wrote it here, I would not post it as a question about SO :)

So the question is: Can I base the border color in the background attribute dynamically, and if so, how?

+8
html background-color css sass
source share
3 answers

Although this is not a SASS solution, you can just use rgba.

 .border { border: 2px solid rgba(0,0,0, 0.25); } 

See jsfiddle for an example.

+18
source share

I would use mixin like this:

 .darkenBorder(@color) { &.border { background: darken(@color, 20); } } 

This way you can easily add a dark border style to any color:

 .blue { background: #00f; .darkenBorder(#00f); } .red { background: #f00; .darkenBorder(#f00); } 

Even simpler (or more DRY, at least) using the same idea:

 .colorStyles(@color) { background: @color; &.border { background: darken(@color, 20); } } .blue { .colorStyles(#00f); } .red { .colorStyles(#f00); } 

<h / "> Output:

 .blue { background: #00f; } .blue.border { background: #000099; } .red { background: #f00; } .red.border { background: #990000; } 
+5
source share

as already mentioned, I would go for it, but with a safe reset from background-clip; :

 .border { border: 2px solid rgba(0,0,0,0.2);/* set here opacity to darken to lighten , use rgba(255,255,255,0.X) , any other color can be used too*/ background-clip:border-box; /* make sure bg is layed under border */ } 

Demo


see this as a reminder of using rgba () colors since hsla () colors

+1
source share

All Articles