Bootstrap is a popular choice among web developers for building interactive webpage designs. Bootstrap has come along a long way with multiple releases and enriched content with every new release. Bootstrap has a wide community that has also contributed newer packages that have made working with Bootstrap easier. In this article, we shall deal with changing the background color of the toggle switch in Bootstrap 4. Bootstrap 4 provides a custom-switch class by default which is used to create toggle switch and the custom-control-input class deals with the background color and border color of the switch. In Bootstrap 4, the background color of the toggle switch is blue. This color can be changed by manipulating the custom-control-input class. There is another method to change the color using external libraries with a wide range of color classes. We shall discuss both the methods in the examples below.
This approach creates the toggle switch using the predefined custom-switch class and the color is altered by specifying the required color in the custom-control-input classes. This method includes a great deal of coding as one must repeat the entire code for a different color. This makes it cumbersome.
The second method eliminates the extra efforts required in the first method to specify the color changes for each and every custom-control-input class. This is a better and sophisticated approach as it does not include lengthy coding. The method makes use of the Bootstrap Switch Button package available on Github. It is an open-source library and works with all Bootstrap 4 components. This library has predefined classes that help us define a color for the toggle switch. The data-onstyle attribute of the input tag is responsible for setting the toggle switch color. The color options available are similar to Buttons in Bootstrap 4. The data-toggle attribute specifies that the checkbox is a switch button and the data-width attribute specifies the width of the toggle switch. The checked attribute denotes that when the page loads the switch is already checked and can be unchecked as per requirement.