Bootstrap Utilities: Margins and padding

Bootstrap also provides handy classes for centering and floating elements.

Bootstrap 3 had a center-block class, which used margins to align an element centrally and set the display property to block. This has been removed from Bootstrap 4 in favor of two other classes: d-block and mx-auto. As already noted earlier, the d-block class is responsible for setting the element’s display property to block, while the mx-auto class sets the margin properties to auto. Similarly, the mt-auto, mr-auto, ml-auto, and mb- auto classes set the margin-top, margin-right, margin-left, and margin-bottom properties to auto respectively (the classes are defined in _spacing.scss):

.m-auto {

margin: auto !important;

}

.mt-auto {

margin-top: auto !important;

}

.mr-auto {

margin-right: auto !important;

}

.mb-auto {

margin-bottom: auto !important;

} .ml-auto {

margin-left: auto !important;

}

.mx-auto {

margin-right: auto !important;

margin-left: auto !important;

} .my-auto {

margin-top: auto !important;

margin-bottom: auto !important;

}

As you can observe, margin helper class names take the form of <first letter of property name><direction>-<value>. By adhering to this naming convention, we can either clear or increase the margins of an element. For example, m-o sets the value of the margin property to 0, mt-0 sets margin-top to 0, mr-0 sets margin-right to 0, m-1 sets the margin to 0.25rem, and so on and so forth (refer to Table 8.1—note that there exist responsive equivalents for each of the listed classes that take the form of m*-*-*. For example, to set the margin property to 0, we use the m-0 class. To set the margin property to 0 for small viewports however, you can use the m-sm-0 class):

Table 8.1: The available margin helper classes at a glance

Similar to the margin helper classes, Bootstrap offers padding helper classes to set the padding of an element. The class names take the form of p*-*; take a look at table 8.2 (note that there exist responsive equivalents for each of the listed classes that take the form of p*­*-*. For example, to set the padding property to 0, you use the p-0 class.

To set the padding property to 0 for small viewports however, you can use the p-sm-0 class):

Table 8.2: The available padding helper classes at a glance

Source: Jakobus Benjamin, Marah Jason (2018), Mastering Bootstrap 4: Master the latest version of Bootstrap 4 to build highly customized responsive web apps, Packt Publishing; 2nd Revised edition.

Leave a Reply

Your email address will not be published. Required fields are marked *