Explain Codes LogoExplain Codes Logo

Twitter bootstrap hide element on small devices

html
responsive-design
visibility-control
bootstrap
Alex KataevbyAlex Kataev·Oct 30, 2024
TLDR

In Bootstrap, to hide content on screens smaller than 576px, utilize a handy duo: d-none d-sm-block. With d-none, it’s invisible by default, but then d-sm-block returns it to the spotlight on small (≥576px) to larger screens.

Example:

<div class="d-none d-sm-block">Harry Potters invisibility cloak for screens < 576px</div>

Essentially, this element becomes the Harry Potter of your webpage, going invisible on xs devices, reappearing from the sm devices upwards.

Device-specific visibility control

Whether it's a mobile or a widescreen monitor, not all devices are meant to display all elements. Let's look at how we can control which elements appear on which devices.

  • Extra Small devices (xs): Use d-none to conceal elements, perfect for mobile-first designs.
  • Small devices (sm): Use d-sm-none to hide elements on smaller screens (under 768px).
  • Medium devices (md): Utilize d-md-none when you want to hide content on tablets.
  • Large (lg) and Extra Large (xl) devices: Handle large display scenarios with d-lg-none or d-xl-none.

Adhering to Bootstrap’s 12-column grid system keeps your layout consistent across different screen sizes.

Masterclass on responsive patterns

Achieving responsive perfection isn't just about cloaking elements. It’s also about adjusting the remaining content to fill the space mindfully.

Dynamic resizing and sharing space

When one star decides to take a break, we must let the remaining shine through and take up space:

<div class="col-6 col-sm-4">//Relaxed on all devices but xs, has its coffee</div> <div class="col-6 col-sm-4">//Always visible, didn't get the memo about xs</div> <div class="col-sm-4 d-none d-sm-block">//Lazy on xs, active on sm and up!</div>

Avoiding unexpected shifting

To dodge the awkwardness of unexpected shifting on varied devices, you need to be a good column width allocator:

<div class="col-12 col-sm-6 col-lg-3">//Born ready- scales with viewport</div>

Embracing structural transformations

Sometimes, it’s about reshuffling. Take horizontal menus for instance. On small screens, evolve them into dropdowns. Stack columns vertically in a narrow viewport. Usability matters!

Consider these when migrating

Each Bootstrap version has its own preferences for visibility classes. Bootstrap 3 enjoys .hidden-xs, while Bootstrap 4 fancies .d-none. The migration guide is your friend, get to know each other well.

Screen reader accessibility adaptations

Even when elements go invisible, screen readers might still spill the beans. Remember to include ARIA attributes or alternate methods to manage how screen readers interact with hidden content.