How to Add Opacity Cross Browser

Sometimes we need to set opacity in our CSS code. The opacity property sets the level of transparency of an element. This property allows us to make an element fully transparent, default or half-transparent.

The number ranges between 0 and 1. For example, the value of 1 makes the element fully opaque, and 0 makes the element fully transparent. A value between 0 and 1 gradually makes an element clear.

How to set the opacity

Use the following:

.opacity {
  opacity: 0.5;
}

We need to write the same code for all browsers.

Here is the code of opacity for cross browsers:

.opacity{
  -moz-opacity: 0.5;/* Netscape */
  -khtml-opacity: 0.5; /* Safari 1.x */
  opacity: 0.5; /* Good browsers */
}

We need to add this code in our CSS file for opacity.

Example of setting opacity for cross browsers:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      img.a {
        opacity: 1;
        -moz-opacity: 1;
        -khtml-opacity: 1; /* Safari 1.x */
      }
      img.b {
        -moz-opacity: 0.5;
        -khtml-opacity: 0.5; /* Safari 1.x */
        opacity: 0.5; /* Good browsers */
      }
    </style>
  </head>
  <body>
    <h1>Example of opacity property</h1>
    <h3>Opacity: 1.0;</h3>
    <img src="/uploads/media/default/0001/01/4982c4f43023330a662b9baed5a407e391ae6161.jpeg" alt="house" width="300" height="200" class="a">
    <h3>Opacity: 0.6;</h3>
    <img src="/uploads/media/default/0001/01/4982c4f43023330a662b9baed5a407e391ae6161.jpeg" alt="house" width="300" height="200" class="b">
  </body>
</html>

Result

Opacity: 1.0; Opacity: 0.6;
Do you find this helpful?

Related articles