I'm working on upgrading an existing application from Bootstrap 4 to Bootstrap 5. I used the occasion to clean up the CSS logic. One thing I had in the original application was an image in the header that should be cropped on smaller screens.
This how the header looks like on bigger screens:
And this is on smaller screens:
The trick I used originally was by using a media queries:
However with the upgrade to Bootstrap 5 I would try to achieve the same thing using the built-in grid system and breakpoints.
Breakpoints
Breakpoints are the building blocks of responsive design in Bootstrap. You can use them to control when your layout can be adapted at a particular viewport or device size.
Bootstrap includes six default breakpoints, sometimes referred to as grid tiers, for building responsively. These breakpoints can be customized if you’re using our source Sass files.
Breakpoint | Class infix | Dimensions |
X-Small | None | <576px |
Small | sm | ≥576px |
Medium | md | ≥768px |
Large | lg | ≥992px |
Extra large | xl | ≥1200px |
Extra extra large | xxl | ≥1400px |
Show/hide images
To show/hide images on certain breakpoints we need to set a combination of the following classes on your image tags:
SCREEN SIZE CLASSES
---------------------------------------------------
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 d-xxl-block
hidden only on xxl d-xxl-none
hidden below sm d-none d-sm-block
hidden below md d-none d-md-block
hidden below lg d-none d-lg-block
hidden below xl d-none d-xl-block
hidden below xxl d-none d-xxl-block
---------------------------------------------------
visible on all d-block
visible only on xs d-block d-sm-none
visible only on sm d-none d-sm-block d-md-none
visible only on md d-none d-md-block d-lg-none
visible only on lg d-none d-lg-block d-xl-none
visible only on xl d-none d-xl-block d-xxl-none
visible only on xxl d-none d-xxl-block
visible below sm d-sm-none
visible below md d-md-none
visible below lg d-lg-none
visible below xl d-xl-none
visible below xxl d-xxl-none
In our specific example, we want to show one image only on xl
or higher dimensions and show the other image only when the dimension is smaller then xl
. Here is how I did this in html: