Border color based on background

asfallows picture asfallows · Apr 10, 2014 · Viewed 9.5k times · Source

I frequently take advantage of darken and lighten in my SASS styles. I'm currently writing a class which will have a border, but will depend on another class for background color. What I want to do is set the border color to a darken of the element's background color.

Something like this:

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

.border { border: 2px solid darken(background, 20); }

Then the markup would 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 as I have it written here, I wouldn't be posting this as a question on SO :)

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

Answer

user3341679 picture user3341679 · Apr 10, 2014

While not a SASS solution, you could just use rgba.

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

See this jsfiddle as an example.