Bootstrap Images

Images should fit in their container and not break the layout on a small screen. Bootstrap gives a few classes to make images responsive and to change their shape. In the examples, a placeholder picture is used, and in your code you write the path of your real image.

Responsive images

Add .img-fluid to an image. It sets max-width: 100% and height: auto, so the image becomes smaller when its parent is smaller, but it is never bigger than its real size.

<img src="images/photo.jpg" class="img-fluid" alt="A placeholder image which scales with its parent">
Live preview

Image shapes

<img src="images/photo.jpg" class="rounded" alt="Rounded corners">
<img src="images/photo.jpg" class="rounded-circle" alt="A circle">
<img src="images/photo.jpg" class="img-thumbnail" alt="A thumbnail with a border">
Live preview

ClassEffect
.roundedRounded corners
.rounded-circleA circle (use it on a square image)
.rounded-pillVery round corners on a wide image
.img-thumbnailA light border and some padding

Align images

<img src="images/photo.jpg" class="rounded float-start me-3" alt="Float left">
<p>The image is on the left, and this text goes around it. Use <code>float-start</code> or <code>float-end</code>, and add a margin so the text is not too close. Use <code>clearfix</code> on the parent if it must contain the floated image.</p>
<div class="clearfix"></div>
<img src="images/photo.jpg" class="rounded mx-auto d-block mt-2" alt="Centered image">
Live preview

To center an image, make it a block with d-block and use mx-auto. Or put it in a parent with .text-center.

Figure with a caption

<figure class="figure">
  <img src="images/photo.jpg" class="figure-img img-fluid rounded" alt="A figure with a caption">
  <figcaption class="figure-caption text-end">A caption for the image.</figcaption>
</figure>
Live preview

Ratio: keep the shape of videos and maps

The ratio helper keeps the aspect ratio of an embedded video, a map or any box, while it scales.

<div class="ratio ratio-16x9" style="max-width: 400px">
  <div class="bg-dark text-white d-flex align-items-center justify-content-center">16 by 9 box</div>
</div>
Live preview

For a YouTube video, put the iframe inside .ratio.ratio-16x9. The other ratios are ratio-1x1, ratio-4x3 and ratio-21x9.

Responsive images with picture

<picture>
  <source srcset="images/photo-large.webp" media="(min-width: 992px)">
  <img src="images/photo-small.webp" class="img-fluid" alt="Description of the image">
</picture>

Tips

  • Always write a useful alt text.
  • Compress the images, and use modern formats like WebP.
  • Use loading="lazy" for the images below the fold.
  • Set the width and height attributes to avoid layout jumps.
Note: The old class .rounded-sm and .rounded-lg of Bootstrap 4 are now .rounded-1 and .rounded-3. Next: Tables.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.