CSS

【opacity,visibility,display】Methods to Toggle the Visibility of Elements with CSS

There are several methods to toggle the visibility of elements using CSS. Each method involves specific property combinations, and it’s essential to choose the right one based on the use case. This article organizes and summarizes the most commonly used methods.

 

CSS Properties for Toggling Visibility

I mainly use the following properties:

  • opacity
  • visibility
  • display

The reason for using these properties is that implementing them with CSS is simpler and more efficient than using JavaScript or jQuery. Don’t you agree that simpler CSS implementations are better?

Now, let’s look at each method in detail.

 

Toggling Visibility While Occupying the Element’s Space

We will summarize two methods for toggling visibility while occupying the element’s space.

 

①Toggling Visibility with Animation

See the Pen
rNadzmZ
by りん@webコーダー (@rinblog0408)
on CodePen.

 

Features

  • The visibility toggle includes animation.
  • The space is not occupied when hidden.
  • transition is possible.

 

Use Case

I frequently use this when creating landing pages. Adding animation to the visibility toggle makes transitions smoother and more natural. It’s especially useful for large spaces where abrupt toggles might feel jarring.

 

②Toggling Visibility without Animation

See the Pen
MWYVvLz
by りん@webコーダー (@rinblog0408)
on CodePen.

 

Features

  • The visibility toggle lacks animation.
  • The space is not occupied when hidden.
  • transition is not possible.

 

Use Case

This method is suitable for simple visibility toggles without animation. It’s ideal for cases where animation isn’t needed.

 

Toggling Visibility Without Occupying the Element’s Space

We will summarize two methods for toggling visibility without occupying the element’s space.

 

③Toggling Visibility with Animation

See the Pen
xxbWXEw
by りん@webコーダー (@rinblog0408)
on CodePen.

 

Features

  • The visibility toggle includes animation.
  • The space is still occupied when hidden.
  • transition is possible.

 

Use Case

Use this method when you want to toggle visibility smoothly without affecting the layout. It’s great for a seamless visible/invisible switch.

 

④Toggling Visibility without Animation

See the Pen
oNgqGWY
by りん@webコーダー (@rinblog0408)
on CodePen.

 

Features

  • The visibility toggle lacks animation.
  • The space is still occupied when hidden.
  • transition is possible.

 

Use Case

This method is useful for immediate visibility toggles without affecting the layout. It’s best for straightforward visibility changes.

 

Conclusion

This article covered methods for toggling visibility using CSS properties. While JavaScript or jQuery can also achieve this, I find CSS implementations simpler and more efficient. Find the method that works best for you and toggle visibility seamlessly.