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!
Создание Bootstrap кнопок. Настройка цвета и размера
Кнопки — это один из самых распространённых элементов в дизайне сайтов и приложений. В большинстве случаев кнопки применяются для того, чтобы привлечь внимание посетителя сайта к действиям, которые они выполняют. Кнопки используются в HTML формах, диалоговых окнах, меню и во многих других местах веб-страниц.
Для оформления элемента в виде кнопки обычно используется <button> , а также ссылки <a href .
Хорошей практикой является использование ссылок <a href для создания переходов между страницами, а <button> — для выполнения различных действий на странице.
Создание дефолтной Bootstrap кнопки осуществляется посредством добавления к тегу базового класса btn и класса с темой (например, btn-primary ).
В Bootstrap 3 нет темы secondary, light и dark, но есть default.
Outline кнопки (только Bootstrap ?пеж4)
Создание бутстрап кнопки с контуром (без фона) необходимо добавить к элементы классы btn и btn-outline-* :
Изменение размера кнопки
Для увеличения или уменьшения размера кнопки, к ней нужно дополнительно добавить класс btn-{size} . Вместо {size} необходимо указать lg , sm или xs (только в Bootstrap 3).
Класс btn-lg предназначен для создания большой кнопки, sm — маленькой и xs — очень маленькой.
Кнопка, занимающая всю ширину родительского элемента
Создание кнопки с шириной равной ширине родительского элемента осуществляется с помощью класса btn-block.
Активное состояние кнопки
Если необходимо отображать кнопку нажатой (с более тёмным фоном и рамкой), то к ней необходимо добавить класс active .
Для поддержки вспомогательных технологий к кнопке нужно добавить атрибут aria-pressed=»true» .
Неактивное состояние кнопки
Если необходимо отключить возможность нажатия на кнопку, то её необходимо перевести в неактивное состояние.
Для элемента button это действие осуществляется посредством добавления к нему атрибута disabled .
Для отключения функциональности кнопки, созданной с помощью элемента a , необходимо выполнить немного другое действие, а именно добавить к ней класс disabled .
Класс disabled отключает возможность клика по кнопке посредством установки ей (элементу a ) CSS-свойства pointer-events со значением none .
Для обеспечения поддержки вспомогательных технологий, таких как программ чтения с экрана, к кнопке (элементу a ) необходимо добавить атрибут aria-disabled = «true» .
Плагин Buttons
Компонент «Buttons» включает в себя не только CSS, но JavaScript. Данный код (buttons.js) добавляет на страницу функционал, предназначенный для управления состоянием кнопок, как отдельных, так и находящихся в группах.
Использование кнопки в качестве переключателя
Для создания кнопки-переключателя добавьте к ней атрибут data-toggle=»button» . После этого при нажатии на кнопку она будет переключаться из обычного состояния в активное и наоборот.
Если кнопка изначально должна находиться в активном состоянии, то к ней необходимо добавить класс active и aria-pressed=»true» .
Checkbox и radio кнопки
CSS-стили Buttons можно применить и к другим HTML элементам, таким как к label , чтобы создать checkbox или radio кнопки.
Атрибут data-toggle=»buttons» предназначен для JavaScript. Он используется в его коде в качестве селектора для выбора элементов, к которым необходимо добавить поведение «переключения».
Состояние кнопок обновляется через событие click . Если необходимо использовать какой-то другой способ для обновления состояния checkbox или radio кнопок , то его нужно написать самостоятельно.
Класс btn-group-toggle (Bootstrap 4) предназначен для стилизации элементов input внутри группы.
Методы плагина Buttons
В Bootstrap 3 и 4 версии имеется метод $().button(‘toggle’) . Он предназначен для программного переключения состояния одной или нескольких кнопок.
Например , создадим 2 кнопки, и с помощью одной кнопки будем переключать состояние другой:
В Bootstrap 3 кроме вышеприведённого метода имеются ещё 2:
- $().button(‘string’) — изменяет текст кнопки на значение, хранящееся в атрибуте data-string-text (имя атрибута составляется путём сложения строки data- , строкового значения , переданного в функцию button, например string и строки -text );
- $().button(‘reset’) — заменяет текст на изначальный.
Пример работы с методами $().button(‘complete’) и $().button(‘reset’) .
Этот пример состоит из 2 кнопок.
При нажатии на первую кнопку её текст изменяется на значение атрибута data-complete-text . Это действие выполняется с помощью метода $().button(‘complete’) .
При нажатии на вторую кнопку текст первой кнопки заменяется на изначальный. Осуществляется это посредством метода $().button(‘reset’) .
Выравнивание кнопки по центру
Кнопка в Bootstrap 3 и 4 по умолчанию отображается как inline-block . Это обстоятельство и определяет способы, с помощью которых её можно выровнять по центру.
Первый способ — это обернуть кнопку элементом , который показывается в документе как блочный (т.е. у которого CSS-свойство display , равно значению block ), и добавить к нему класс text-center .
Второй способ — это изменить отображение кнопки на блочное и добавить к ней стили margin-left: auto и margin-right: auto . В Boostrap 3 — это действие можно выполнить с помощью класса center-block , а в Bootstrap 4 — посредством классов d-block и mx-auto .
Выравнивание кнопки по левому или правому краю
Способы выравнивания кнопки по левому или правому краю в Bootstrap 3 и 4 показаны в нижеприведенных примерах.
Как создать круглую кнопку
Для создания круглой кнопки необходимо установить с помощью CSS ей одинаковую ширину и высоту. Радиус скругления в этом случае нужно задать, равный половине ширины или высоты.
Если необходимо содержимое кнопки расположить на нескольких строчках (например, иконку на одной, а текст на другой), то значение CSS свойства white-space необходимо сбросить или другими словами восстановить ему значение по умолчанию.
CSS Button Size
In this example, we will use the width and height property for the button element to increase its size. We will use the CSS Style Tag approach in this example to add several properties. First, we will look at the default size of the button element present in an HTML file.
As we can see in the given script, we have not altered the size of the button. In the following output, we can see that the button size is very small and is not feasible for a web page.

So, now we add the styling to the button. First, we open the head tag for the file. In this tag, the style tag for CSS is called. In this tag, we add all the properties for the button element. We write all the properties for the button element inside the button class parenthesis. First, we set the background color to “yellow”. Then, we set the width in pixel format to “100px”. Finally, we set the height in pixel format to “30px”. We close the style and head tags after all of the formatting are complete. Then, we go to the body tag. We write the page’s headline using the h1 tag in the body tag and then open the button tag. The class from the style tag is called in the button tag. Following that, we close the button tag with the text that displays on the button in between, as well as the body tag.

As explained earlier, we added the code in the previous script. Now, we open this new script on our browser after saving it in the correct format.

In the given output, we can see that the button has all the formatting including the size that we specified in the style class in the file header.
Example 02: Using Inline CSS to Alter the Size of a Button in an HTML File
In this example, we will use the inline CSS to change the size of an HTML file’s default button element. All the style properties will be assigned inside the button tag. This is an unconventional method to add CSS to any element and will only be associated with the current element.

As we can see in the previous snippet, we directly moved to the body of the file as all the content would be in the body tag. First, we open the h1 tag to write a heading for the page and then close it. Then, we open the button tag. In this tag, we call the style attribute by its keyword. After this, we write all the properties for the button element in the inverted commas and separate them by using the semicolon character. First, we assign the background color, “yellow”. Then, we assign the width in the pixel format. In the end, we assign the height, also in the pixel format. After this, we close the button tag with the text in between, which will appear on the button. And close the body tag along with it. Now, we save this file in the “.html” format and open it on our browser to get the following result:

As we can see in the output of our script, the heading and button from the body tag are visible. The button has all of the values defined in the tag, including the height and width.
Example 03: Increasing the Size of a Button When It Hovers With Our Cursor in an HTML File
In this example, we will use the width and height properties of the button element to make it bigger, only when the pointer is over it. In this example, we will use the CSS style tags to add numerous attributes and effects to the button element.

In this example, we customize the button using the CSS style tags. First, we open the file’s head tag. And then, we call the CSS style tag from there. We add all of the button element’s attributes in this tag. Inside the button class parenthesis, we enter all of the properties for the button element; in this example, we set the background color to “yellow.” Then, we open a button class that inherits a method called “hover”. In this function, we do the following: we set the width in pixel format to “100px” and set the height in pixel format to “30px”. After we finish formatting, we close the style and head tags. Then, we go to the body tag. We use the h1 tag to create the page’s title in the body tag, then open the button tag. The button tag uses the class from the style tag and have the text that appears on the button in between. Following that, we close the button tag and the body tag.

As we can see in the previous output, the size and the background color have changed as we hovered on the button with our cursor. This is because the hover function has all these properties defined in the style tag of the header’s file.
Example 04: Using the Font Size to Enhance the Size of a Button Using CSS
In this example, we will opt to a different method to change the size of a button. The font size property will be used to increase the size of a button using the style tag CSS.

First, we open the style tag in the file header and create a styling class for the button. In this class, we assign a background color to the button. After that, we assign the font size as well. In this case, it is set to “25px”. Then, we close the class and the style and head tags, respectively. Then the body tag has a heading and a button tag which have the style tag class inherited in it. After this, we close the tags and save the file to open it on our browser.

In the output screen, we can see that the button has an increased size from the default button that the HTML provides due to the change in the font size property.
Conclusion
In this article, we discussed the size of the button element present in the Hypertext Markup Language. The default button has a very small size which makes it difficult to navigate on a web page. So, we used the different approaches in CSS like the style tag and inline CSS approach. The most common property used to alter the size are the width and height property of a button. We discussed this concept and implemented this on the Notepad++. We also implemented the font size approach to increase the size of a button.
About the author

Aqsa Yasin
I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.
Resizing a button
I have a «button» that I wish to use all throughout my site, but depending on where in the site the button is, I want it to display at different sizes.
In my HTML I have tried (but its not working):
And the matching CSS:
I assumed that if each time I call this class I can just pass in a size and hey-presto. but not.
By adding the width and height as I call the button class seems to do nothing to the size of it. Does anyone know how I can do this? And if I put the width and height in the CSS then the button will be the same size everywhere.
![]()
5 Answers 5
You should not use «width» and «height» attributes directly, use the style attribute like style=»some css here» if you want to use inline styling:
<div style=»width:60px;height:30px;»>This is a button</div>
Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:
Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons — you’ll only have to change them once in the CSS.