How to use Bootstrap 4 in images

Overview

Images are essential part of a website because they convey a lot of information and make websites attractive. But adding images and making them responsive can be a tiring task using CSS.

Bootstrap 4 comes with predefined images classes for making our responsive.

Image classes

The img tag is used to include an image in our website. We can style this tag with the Bootstrap 4 classes that are categorized in terms of the functions they perform below:

  1. Shapes: These classes give our images its shapes. They include :
  • .rounded: This adds rounded corners to our image.
  • .rounded-circle: This turns our images into a circle.
  • .thumbnail: This adds borders to our image thus shaping it into a thumbnail.
  1. Alignment : These classes decide the floating attribute of our images. They include:
  • .float-right: This floats our image to the right.
  • .float-left: This floats it to the left.

Note: To place an image to the center, we use the utility classes .mx-auto and .d-block in the img tag. .mx-auto utilizes the margin: auto while .d-block utilizes display: block.

  1. Responsive image: This class enables an image to automatically adjust to fit the size of various screens. A responsive image can be created by simply adding the .img-fluid class to the img tag. The .img-fluid applies max-width: 100% and height: auto to the image.

Explanation

Immediately above is a rounded image placed at the center of a page.

  • Line 10: An img was included with the following classes: .img-fluid, .rounded-corner, .mx-auto, d-block.
  1. .img-fluid- makes the image responsive.
  2. .rounded-circle- shapes it into a circle.
  3. .mx-auto and .d-block- centered the image.

Note: The src specifies the image source while the alt attribute is an alternative text of the image in case the source is not found.

Free Resources