0
0
CSSmarkup~5 mins

Visibility property in CSS

Choose your learning style9 modes available
Introduction

The visibility property lets you control if an element is seen or hidden on the page without changing the layout around it.

You want to hide a button but keep its space so the page layout doesn't jump.
You want to temporarily hide a message but keep the area reserved for it.
You want to make an image invisible but keep the space it occupies for design balance.
You want to toggle visibility of a menu without shifting other content.
You want to hide text for accessibility reasons but keep the layout stable.
Syntax
CSS
selector {
  visibility: visible | hidden | collapse | initial | inherit;
}
visible means the element is shown.
hidden means the element is invisible but still takes up space.
Examples
This makes the paragraph visible on the page.
CSS
p {
  visibility: visible;
}
This hides the div but keeps its space reserved.
CSS
div {
  visibility: hidden;
}
This hides a table row and removes its space in supporting browsers.
CSS
tr {
  visibility: collapse;
}
Sample Program

This example shows three boxes stacked vertically. The green box is visible, the red box is hidden but still takes space, and the black border box is visible. You can see the space where the red box is even though you can't see the box itself.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Visibility Property Example</title>
  <style>
    .visible-box {
      width: 8rem;
      height: 8rem;
      background-color: #4caf50;
      visibility: visible;
      margin-bottom: 1rem;
    }
    .hidden-box {
      width: 8rem;
      height: 8rem;
      background-color: #f44336;
      visibility: hidden;
      margin-bottom: 1rem;
    }
    .border-box {
      width: 8rem;
      height: 8rem;
      border: 2px solid #000;
      margin-bottom: 1rem;
    }
  </style>
</head>
<body>
  <div class="visible-box" aria-label="Visible green box"></div>
  <div class="hidden-box" aria-label="Hidden red box"></div>
  <div class="border-box" aria-label="Black border box"></div>
  <p>Notice the red box is invisible but space is still reserved for it.</p>
</body>
</html>
OutputSuccess
Important Notes

Unlike display: none;, visibility: hidden; keeps the space reserved on the page.

The collapse value mainly works for table rows and columns, hiding them and removing their space.

Use aria-label or other accessibility features to describe hidden elements if needed.

Summary

The visibility property controls if an element is seen or hidden.

hidden hides the element but keeps its space.

This helps keep page layout stable when hiding elements.