CSS Function - grayscale()



CSS grayscale() function sets the grayscale of an image or sets an element color to grayscale. It is used with the CSS filter property. The value 0 keeps the original colors, while 100% (or 1) makes the element completely grayscale (black and white).

Syntax

The syntax for the CSS grayscale() function is as follows:

filter: grayscale(amount);

Parameter

CSS grayscale() function accepts a single optional parameter (amount) that specifies the grayscale level. If the amount is not specified, 1 (100%) is used as the default value.

Examples of CSS grayscale() Function

The following examples illustrate the use of the CSS grayscale() function. The grayscale of an image can be adjusted using the CSS grayscale() function.

Setting grayscale of Image

In this example, we have set the grayscale level of an image. The image is displayed at grayscale levels of 0, 50%, and 100%. As we increase the grayscale level, the colors fade, which turns the image to black and white.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>CSS grayscale() Function</title>
    <style>
        .container {
            width: 400px;
            border: 2px solid #04af2f;
            padding: 20px;
            margin: 10px;
            display: inline-block;
        }
        .img1 {
            filter: grayscale(0);
        }
        .img2 {
            filter: grayscale(50%);
        }
        .img3 {
            filter: grayscale(100%);
        }
    </style>
</head>
<body>
    <h2>CSS grayscale() Function</h2>
    <div class="container">
        <h3>Image at grayscale(0%): </h3>
        <img class="img1" src="/html/images/test.png" alt="logo">
    </div>
    <div class="container">
        <h3>Image at grayscale(50%): </h3>
        <img class="img2" src="/html/images/test.png" alt="logo">
    </div>
    <div class="container">
        <h3>Image at grayscale(100%): </h3>
        <img class="img3" src="/html/images/test.png" alt="logo">
    </div>
</body>
</html>

Changing Image to Grayscale on Hover

In this example, we have changed the image to grayscale upon hovering over it.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>CSS grayscale() Function</title>
    <style>
        img:hover {
            filter: grayscale(100%);
        }
    </style>
</head>
<body>
    <h2>CSS grayscale() Function</h2>
    <p>
        <strong>Hover over this image to change it to grayscale.</strong>
    </p>
    <img src="/html/images/test.png" alt="logo">
</body>
</html>

Supported Browsers

Function Chrome Edge Firefox Safari Opera
grayscale() 18 12 35 6 15
Advertisements