W3docs

How to Set Border Opacity with CSS

You can set the border opacity using a RGBA color as a value for the CSS border property. In this snippet, we’re going to demonstrate how it can be done.

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

This tutorial demonstrates how to achieve this effect.

Create HTML

How to Set Border Opacity with CSS

<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.

How to Set Border Opacity with CSS

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

<div class="demo px-2.5 mt-1 mb-5 not-prose">Set a border opacity with CSS</div>

The rgba() function is supported in all modern browsers, making the RGB fallback largely obsolete. However, for legacy browser support, you can provide a non-transparent RGB fallback before the RGBA declaration. Older browsers that do not recognize rgba() will ignore it and use the rgb() fallback, while modern browsers will apply the rgba() value.

Example of setting border opacity with an alternative:

Example of setting border opacity using two border properties:

<!DOCTYPE html>
<html>
  <head>
    <title>The title of the document</title>
    <style>
      div {
        padding: 10px;
        border: 1px solid rgb(246, 176, 177); /* Fallback for older browsers */
        border-top: 1px 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>