Change the Button Color Using Internal Styling
IIn this approach, we are using internal styling to change the button color in HTML by placing the CSS styling properties inside a <style> tag within the HTML document’s <head> section. The classes which are defined in the <style> tag are then applied to buttons using class property. Additionally, the JavaScript is used to dynamically change the color of the button when the user clicks on the buttons.
Syntax:
<style>
// CSS styles using Classes and IDs
</style>
Example: The below example uses internal styling to change the button color in HTML.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title >Example 2</ title > < style > .main-heading { color: green; } .blue-button { background-color: blue; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; margin: 5px; } .red-button { background-color: red; color: white; padding: 12px 18px; border: 2px solid white; border-radius: 8px; cursor: pointer; margin: 5px; } .green-button { background-color: green; color: white; padding: 15px 25px; border: none; border-radius: 3px; cursor: pointer; margin: 5px; } </ style > </ head > < body > < h1 class = "main-heading" >w3wiki</ h1 > < h3 >Using Internal Styling</ h3 > < button class = "blue-button" onclick = "colorFn('blue-button', 'purple')" > Click me </ button > < button class = "red-button" onclick = "colorFn('red-button', 'orange')" > Click me </ button > < button class = "green-button" onclick = "colorFn('green-button', 'yellow')" > Click me </ button > < script > function colorFn(buttonClass, newColor) { const btns = document.getElementsByClassName(buttonClass); for (let i = 0; i < btns.length ; i++) { btns[i] .style.backgroundColor = newColor ; } } </script> </ body > </ html > |
Output:
How to Change the Button Color in HTML ?
Styling of elements enhances the visual appearance and improves the overall user interface. We can change the button color in HTML using different approaches as listed below.
Table of Content
- Using Inline Styling
- Using Internal Styling