How to Change Button Size with JavaScript or CSS (3 Ways!)
I will show three examples of changing an HTML button’s size. Two of these use JavaScript and one is mostly CSS.
The buttons start with min-width: 240px
and no set height.
Before we explore the technical how-to, I want to mention that it is usually good practice to set button min-width
rather than width. This makes buttons mobile responsive and more web accessible.
However, if you have a use case where you want to change button size (width and height) using JavaScript, read on!
Statically Change Button Size with JavaScript
Button height and width can be updated using JavaScript and accessing the style
attribute of the button. This uses JavaScript to apply inline styling to the button.
We add the usual click listener and click handler. Inside the click handler it gets interesting. We take the passed button and update jsButton.style.width = "300px";
and jsButton.style.height = "100px";
.
We can see in dev tools that this overrides the 240px width set by my button selector in my CSS file:
And we can see that it is applied with inline styling.