Can you set a border opacity in CSS?

Unfortunately the opacity property makes the whole element (including any text) semi-transparent. The best way to make the border semi-transparent is with the rgba color format. For example, this would give a red border with 50% opacity:

div {
    border: 1px solid rgba(255, 0, 0, .5);
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

For extremely old browsers that don’t support rgba (IE8 and older), the solution is to provide two border declarations. The first with a fake opacity, and the second with the actual. If a browser is capable, it will use the second, if not, it will use the first.

div {
    border: 1px solid rgb(127, 0, 0);
    border: 1px solid rgba(255, 0, 0, .5);
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}

The first border declaration will be the equivalent color to a 50% opaque red border over a white background (although any graphics under the border will not bleed through).

I’ve added background-clip: padding-box; to the examples above to ensure the border remains transparent even if a solid background color is applied.

Leave a Comment