The difference between the CSS visibility and display properties

The visibility and display properties are both CSS properties that are used to control the visibility of elements on a web page, but they function in slightly different ways.

The visibility property is used to toggle the visibility of an element, but it does not affect the layout of the page. When an element's visibility is set to hidden, the element will be invisible, but it will still take up the same amount of space as if it were visible. This means that if you have an element that is set to visibility: hidden, it will still push other elements around it, as if it were still visible.

On the other hand, the display property is used to toggle the display of an element and it also affects the layout of the page. When an element's display is set to none, the element will be hidden, and it will also not take up any space on the page. This means that if you have an element that is set to display: none, it will not push other elements around it, as if it were not there.

To sum up:

  • visibility property keeps the element in the layout and it just hides the content but still takes space.
  • display property removes the element from the layout and it doesn't take space anymore.

Here's an example of how the two properties differ:

<div class="box-1">Box 1</div>
<div class="box-2">Box 2</div>

.box-1 { visibility: hidden; } .box-2 { display: none; }

In this example, box 1 will not be visible but it will still take up space and push box 2 down, while box 2 will not be visible and will not take up any space on the page, so box 1 will not be affected.

It is important to note that the visibility property only has 2 values: visible and hidden, while the display property has many more values such as block, inline, inline-block, table, flex and grid to name a few. Each of these display values has its own set of properties and layout behaviors.

In general, the visibility property is used for cases where you want to hide an element but keep it available to screen readers or for when you want to change the visibility of an element in response to a user interaction. On the other hand, the display property is used for cases where you want to control the layout of the page or to hide an element permanently from the page.

Additional resources
  • Frontend web development courses

    Beginner-friendly courses focusing on HTML, CSS, and JavaScript.

    View Courses
  • Frontend web development projects

    Beginner-friendly projects focusing on HTML, CSS, and JavaScript.

    View Projects
  • Free website templates

    Collection of free, high-quality website templates for your next project.

    View Templates