How to make a transparent border?

Ellen Probst
3 min readFeb 5, 2017

--

A few days ago I tried adding a transparent border to a div element. I thought this was going to be pretty easy and assumed I could get the result by simply giving the border-color an rgba value. However, it didn’t do what I thought it would do because the border was not showing the underlying element at all.

Here’s an example of what happened:

rgba(150, 0, 0, 0.5)

This is what I thought would happen:

Border-color and rgba

So why is rgba not working on the border-color? Well, it does work but not as you might expect. Let’s take a closer look at what happens when you use rgba. Say we have a box with a background color of dark cyan and a red border.

This is the initial box with rgba(150, 0, 0, 1)

Now let’s set the border opacity to 50% by changing the rgba value:

.box {
width: 200px;
height: 200px;
background: darkcyan;
border: 50px solid rgba(150, 0, 0, 0.5);
}
rgba(150, 0, 0, 0.5)

Our red border turned grey and doesn’t look transparent. What happens when we set the opacity even lower to 20%?

rgba(150, 0, 0, 0.2)

Now our border is changing its color to dark cyan. Confusing, right?

The border transparency is showing the element’s own background color

Here’s what’s happening: the border transparency is showing the element’s own background color underneath the border. In this case, because our box has a background color of dark cyan, the border is revealing the dark cyan.

Let’s try box-shadow

So how can we set a transparent border and have the underlying element, our image, reveal instead? There’s a couple of ways to do this, one of which is by using the box-shadow property. Unlike the border, the box-shadow sits outside of the element so it won’t reveal the dark cyan but rather the element underneath.

Box-shadow takes four values: offset-x, offset-y, blur-radius, spread-radius and color.

All we need to do now is set the offset and blur-radius to 0, add a spread-radius and rgba color with a 50% opacity. That’s how we get that clean transparent border.

.box {
width: 200px;
height: 200px;
background: darkcyan;
box-shadow: 0 0 0 50px rgba(150, 0, 0, 0.5);
}
This the result we get when using box-shadow

Note: Because the box-shadow sits outside of the element it’s not part of the element’s box-model. This means that it is not calculated in the element’s width and height, it’s literally just being attached to the element. The border on the other hand is part of the box-model and when using together with box-sizing, the element dimensions will include the border.

--

--