How to hide elements in Bootstrap 4

Overview

Creating a perfect mobile-friendly website can be challenging, as different elements behave differently depending on the screen sizes.

One of the easiest adopted ways to create a mobile-friendly website is to hide and show elements. We can do this either with CSS, or with Bootstrap 4.

Hiding elements with CSS

Two different properties in CSS let us hide elements:

  1. visibility: hidden;: This property removes the element from the document flow and leaves a big hole in its place. However, other elements behave as if the hidden element is still there.

  2. display: none;: This property removes the element from the document flow, and other elements behave as if the hidden element is not there.

Note: We can build a mobile-friendly website by hiding some elements in a certain breakpoint, and replacing them with other elements that fit in that particular breakpoint.

Hiding elements with Bootstrap 4

There are two ways of hiding elements in Bootstrap 4:

  1. Using the .invisible class: The .invisible class adds visibility: hidden to the element. Thus, it removes the element from the document flow, and leaves a big hole in its place.
  2. Using the d-*-none class: The asterisk (*) in the d-*-none class represents the four responsive screen size options available in Bootstrap 4: sm, md, lg, and xl. Adding any of these to this class will automatically hide the specified screen size elements.

The table below shows how to hide elements on various screen sizes:

Screen size Class
Hidden on all .d.none
Hidden only on xs .d-none .d-sm-block
Hidden only on sm .d-sm-none .d-md-block
Hidden only on md .d-md-none .d-lg-block
Hidden only on lg .d-lg-none .d-xl-block
Hidden only on xl .d-xl-none

Example

Explanation

  • Line 7: We create h1 with the .invisible class. This hides the element, and leaves a hole in its place in the document flow.
  • Line 8: We create h1 with the d.none class. This hides the element on all devices, without leaving a hole in its place.

Note: We can change the classes in the code widget above to see their effects.

Free Resources