How to hide elements in CSS - Display vs Visibility

How to hide elements in CSS - Display vs Visibility

CSS is a powerful DOM layout tool used by (all?, yes!) Frontend Developers and Developers of the web to arrange pleasing and eye-catching interfaces. From time to time, there are scenarios where you would like to hide an element from your display either conditionally or permanently.

There are many ways of hiding elements in CSS like with the transform property, absolute position and opacity property but in this article, we will be focusing on the display and visibility property

Display Property

The display CSS property sets how an element is treated as a block or inline element and the layout used for its children. Formally, the display property sets an element's inner and outer display types. The attribute of the display property to be used in this case is none. display: none removes the entire element from the page and will affect the layout of the page.
When the display: none property is used, the element hidden is not accessible on the document layout again. Even though the elemnt is still accessible in the HTML source code when inspected, it does not take up any space on the User Interface.

Visibility Property

By default the visbility property of an element in the DOM is set to visible except otherwise stated in the element css properties.

In contrast to the display property, the visibility (hidden) property hides the element while still keeping the space the same. This means the element hidden is not visible but still occupies space in the DOM layout. When the visibility hidden property is used, such element still takes us space in the User Interface and is still accessible on the document layout also accessible in the HTML source code.

We can liken the visibility property to a toggle or switch that determines if an element is to be shown or not. The element and its content are invisible, but still affect the layout of the page as it is not taken off completely.

Let's take a look at some code;

<div class="element__display">
    We intend to hide this element and it's child with the display property.
    <p>This is a paragraph<p>
<div>
.element__display {
    display: none;
}
<div class="element__visibility">
    We intend to hide this element and it's child with the visibility property.
    <p>This is a paragraph<p>
<div>
.element__visibility {
    visibility: hidden;
}

Conclusion

Choosing the right property to hide elements on the web should be dependant on the scenairo or use case. If you want the element to be taken off but not affect your page laoyout then, the visibility property should be your go to and be set to hidden.

As the last takeaway, It is important to note that display: none changes the flow of your layout while visbility: hidden maintains the initial flow of your layout.