How to Set Border Opacity with CSS

As it's known, the CSS opacity property makes the whole element semi-transparent. That’s why we cannot use it to make set the opacity of the border. To set the border opacity, we can use a RGBA color value with the border property.

If you have such difficulty when setting border opacity, you are in the right place. Let’s see how this is done.

Create HTML

<h2>Example</h2>
<div>Set a border opacity with CSS</div>

Add CSS

  • Use the padding property.
  • Add the border property and use a “rgba” value for it.
  • Set the background-clip property to “padding-box” for Firefox 4+, Chrome, and Opera.
  • Use the -webkit- prefix with the background-clip for Safari.
div {
  padding: 10px;
  border: 1px solid rgba(255, 0, 0);
  border-top: 1px solid rgba(255, 0, 0, .3);
  -webkit-background-clip: padding-box;
  background-clip: padding-box;
}

The full example looks like the following.

Example of setting border opacity:

<!DOCTYPE html>
<html>
  <head>
    <title>The title of the document</title>
    <style>
      div {
        padding: 10px;
        border: 1px solid rgba(255, 0, 0);
        border-top: 1px solid rgba(255, 0, 0, .3);
        -webkit-background-clip: padding-box; /* for Safari */
        background-clip: padding-box; /* Firefox 4+, Opera, Chrome */
      }
    </style>
  </head>
  <body>
    <h2>Example</h2>
    <div>Set a border opacity with CSS</div>
  </body>
</html>

Result

Set a border opacity with CSS

However, this method may have some problems, as some browsers don’t understand the RGBA format and won’t display any border at all. For that, we can use two border properties, one of them with RGB, and the other with RGBA color. If possible, the browser will use the second one, if not, the first.

Example of setting border opacity with an alternative:

<!DOCTYPE html>
<html>
  <head>
    <title>The title of the document</title>
    <style>
      div {
        padding: 10px;
        border: 1px solid rgba(255, 0, 0);
        border-top: 2px solid rgb(246, 176, 177);
        border-top: 2px solid rgba(255, 0, 0, .2);
        -webkit-background-clip: padding-box;
        background-clip: padding-box;
      }
    </style>
  </head>
  <body>
    <h2>Example</h2>
    <div>Set a border opacity with CSS</div>
  </body>
</html>