How to add an icon to the Basic Bootstrap 5 button.
Final output:
1. Let’s start with the first button from the official Bootstrap Buttons page.
<button type="button" class="btn">Base class</button>
Output:
2. For a red button, add the Bootstrap class btn-danger. Add some border-radius as well using the rounded-5 Bootstrap class.
<button type="button" class="btn btn-danger rounded-5">Base class</button>
Output:
3. Now let’s add an icon to the button. To use Bootstrap icons first install it. I am using the CDN link. Change the button text.
And now select your icon and place it inside a span element inside the Bootstrap button.
<button type="button" class="btn btn-danger rounded-5">Subscribe
<span>
<i class="bi bi-bell-fill"></i>
</span>
</button>
Output:
4. To style it further, add a background color to the span and change the button text color too.
<button type="button" class="btn btn-danger rounded-5">Subscribe
<span class="bg-light">
<i class="bi bi-bell-fill text-danger"></i>
</span>
</button>
Let’s set equal width and height for the span element. Since span is an inline element it won’t be applied just yet.
button span {
width: 1.8em;
height: 1.8em;
}
Output:
5. Let’s set the button’s display to flex since the span will be flex too, and align items to the center.
<button type="button" class="btn btn-danger rounded-5 d-flex align-items-center">Subscribe
<span class="bg-light">
<i class="bi bi-bell-fill text-danger"></i>
</span>
</button>
Add some left margin for the span element using Bootstrap class ms-2 and the border-radius with class rounded-5.
<button type="button" class="btn btn-danger rounded-5 d-flex align-items-center">Subscribe
<span class="bg-light ms-2 rounded-5">
<i class="bi bi-bell-fill text-danger"></i>
</span>
</button>
Output:
6. Set the display property for span to flex too. To center align the icon horizontally and vertically inside the span element, set the align-items and justify-content properties to center.
<button type="button" class="btn btn-danger rounded-5 d-flex align-items-center">Subscribe
<span class="bg-light ms-2 rounded-5 d-flex align-items-center justify-content-center">
<i class="bi bi-bell-fill text-danger"></i>
</span>
</button>
Output:
Final Output Code for Responsive Bootstrap 5 Button With An Icon:
HTML
<button type="button" class="btn btn-danger rounded-5 d-flex align-items-center">Subscribe
<span class="bg-light ms-2 rounded-5 d-flex align-items-center justify-content-center">
<i class="bi bi-bell-fill text-danger"></i>
</span>
</button>
CSS
button span {
width: 1.8em;
height: 1.8em;
}
Video tutorial for Bootstrap 5 Button With Icon:
If you have any doubts or stuck somewhere, you can reach out through Coding Yaar's Discord server.