Dremendo Tag Line

CSS visibility

Visibility and Opacity

In this lesson, we will learn how to control visibility of an element using the CSS visibility property.

CSS visibility Property

The CSS visibility property is used to an element visible or hidden on a webpage. This property has three values and they are:

  • visible
  • hidden
  • collapse

Let's discuss each value with examples.

video-poster

Making an Element Visible

To make an element visible, you can use the visibility property with the visible value. This is the default value of the visibility property.

Example
.visible-element {
    visibility: visible;
}

Now, any HTML element with the class visible-element will be visible on the webpage.

Hiding an Element

To hide an element, use the visibility property with the hidden value.

Example
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>CSS !important declaration Example</title>

    <!-- Internal CSS -->
    <style>
        #d1 {
            width: 150px;
            height: 100px;
            background-color: yellow;
            visibility: hidden;
        }

        #d2 {
            width: 150px;
            height: 100px;
            background-color: red;
        }
    </style>
</head>

<body>
    <div id="d1"></div>
    <div id="d2"></div>
</body>

</html>

Note: The element with visibility: hidden; will still occupy space on the webpage, but it will not be visible to the user.

Collapsing an Element

The collapse value is mainly used with table rows (<tr>) and row groups (<tbody>, <tfoot>, <thead>) to hide them and remove their space:

Example
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>CSS visibility collapse Example</title>

    <!-- Internal CSS -->
    <style>
        .hidden-element {
            visibility: collapse;
        }
    </style>
</head>

<body>
    <table border="1">
        <thead>
            <tr>
                <th>Header 1</th>
                <th>Header 2</th>
            </tr>
        </thead>
        <tbody>
            <tr class="hidden-element">
                <td>Cell 1</td>
                <td>Cell 2</td>
            </tr>
            <tr>
                <td>Cell 3</td>
                <td>Cell 4</td>
            </tr>
        </tbody>
        <tfoot class="hidden-element">
            <tr>
                <td>Footer Cell</td>
                <td>Footer Cell</td>
            </tr>
        </tfoot>
    </table>
</body>

</html>