DEV Community

Cover image for Bootstrap's media object, but collapsing
Ross Angus
Ross Angus

Posted on • Updated on

Bootstrap's media object, but collapsing

Image above by Eileen Lamb

I love Nicole Sullivan's Media Object (ten years old this year - happy birthday, Media Object!). It's changed a lot since then and on my current sites, I'm using the variant from Bootstrap 4.

However, Media Object has a problem: it doesn't care if you have enough space to display the image and the media-body next to each other or not. If the display gets really, wee, it's just going to crush everything up.

Today I realised that Bootstrap 4's display classes are the solution. Lemmy take you through it.

By default, Media Object in Bootstrap 4 required the following structure:

<div class="media">
  <p class="mr-2"><img src="myimage.jpg" alt=""></p>
  <div class="media-body">
    <h2>Heading</h2>
    <p>Copy</p>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

This particular version of Media Object uses flex for layout, which gives us all kinds of possibilities for positioning the blocks next to each other, or even swapping the order. However, this is all dependent on the .media element having the declaration display: flex.

You want the d

Bootstrap's d classes allow you to switch the display property of an element by breakpoint, starting at the smallest and cascading to the largest breakpoint. For example:

<p class="d-none">
  This won't display at all
</p>
<p class="d-none d-sm-block">
  This appears at <code>sm</code> and larger
</p>
<p class="d-none d-md-block">
  This appears at <code>md</code> and larger
</p>
<p class="d-none d-lg-block">
  This appears at <code>lg</code> and larger
</p>
Enter fullscreen mode Exit fullscreen mode

But it doesn't just switch between block and none. Here's the other values you can apply:

  • none
  • inline
  • inline-block
  • block
  • table
  • table-cell
  • table-row
  • flex <-- foreshadowing
  • inline-flex

Given that, here's how I'm using the d classes in conjunction with Media Object, so it collapses on smaller breakpoints (look at the classes on the .media element):

<div class="media d-block d-md-flex">
  <p class="mr-2"><img src="myimage.jpg" alt=""></p>
  <div class="media-body">
    <h2>Heading</h2>
    <p>Copy</p>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

At smaller breakpoints, none of the flexbox rules applied to the children of media work, because their parent is display: block. However, flexbox kicks in again at the medium (and above) breakpoint.

Hopefully this pattern is useful to someone.

Top comments (0)