I have some buttons on my pure HTML/JS page.
When the page is opened in browser, the button size is normal.
But on refresh/reloading page, the button size is reduced.
In fact, I have not set the button text value. The button’s text is blank.
How should I set the size of my button in HTML irrespective to the size of the text?
Gab
5,4166 gold badges35 silver badges52 bronze badges
asked Jul 29, 2014 at 12:03
Do you mean something like this?
HTML
<button class="test"></button>
CSS
.test{
height:200px;
width:200px;
}
If you want to use inline CSS instead of an external stylesheet, see this:
<button style="height:200px;width:200px"></button>
answered Jul 29, 2014 at 12:08
GabGab
5,4166 gold badges35 silver badges52 bronze badges
5
This cannot be done with pure HTML/JS, you will need CSS
CSS:
button {
width: 100%;
height: 100%;
}
Substitute 100% with required size
This can be done in many ways
answered Jul 29, 2014 at 12:09
button {
width:1000px;
}
or even
button {
width:1000px !important
}
If thats what you mean
answered Jul 29, 2014 at 12:06
If using the following HTML:
<button id="submit-button"></button>
Style can be applied through JS using the style object available on an HTMLElement.
To set height and width to 200px of the above example button, this would be the JS:
var myButton = document.getElementById('submit-button');
myButton.style.height = '200px';
myButton.style.width= '200px';
I believe with this method, you are not directly writing CSS (inline or external), but using JavaScript to programmatically alter CSS Declarations.
answered Sep 5, 2018 at 12:59
I have some buttons on my pure HTML/JS page.
When the page is opened in browser, the button size is normal.
But on refresh/reloading page, the button size is reduced.
In fact, I have not set the button text value. The button’s text is blank.
How should I set the size of my button in HTML irrespective to the size of the text?
Gab
5,4166 gold badges35 silver badges52 bronze badges
asked Jul 29, 2014 at 12:03
Do you mean something like this?
HTML
<button class="test"></button>
CSS
.test{
height:200px;
width:200px;
}
If you want to use inline CSS instead of an external stylesheet, see this:
<button style="height:200px;width:200px"></button>
answered Jul 29, 2014 at 12:08
GabGab
5,4166 gold badges35 silver badges52 bronze badges
5
This cannot be done with pure HTML/JS, you will need CSS
CSS:
button {
width: 100%;
height: 100%;
}
Substitute 100% with required size
This can be done in many ways
answered Jul 29, 2014 at 12:09
button {
width:1000px;
}
or even
button {
width:1000px !important
}
If thats what you mean
answered Jul 29, 2014 at 12:06
If using the following HTML:
<button id="submit-button"></button>
Style can be applied through JS using the style object available on an HTMLElement.
To set height and width to 200px of the above example button, this would be the JS:
var myButton = document.getElementById('submit-button');
myButton.style.height = '200px';
myButton.style.width= '200px';
I believe with this method, you are not directly writing CSS (inline or external), but using JavaScript to programmatically alter CSS Declarations.
answered Sep 5, 2018 at 12:59
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):
<div class="button" width="60" height="100">This is a button</div>
And the matching CSS:
.button {
background-color: #000000;
color: #FFFFFF;
float: right;
padding: 10px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
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.
Kosh
6,0372 gold badges35 silver badges67 bronze badges
asked Jul 27, 2012 at 14:04
1
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 class="button" 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:
.button {
background-color: #000000;
color: #FFFFFF;
padding: 10px;
border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
margin:10px
}
.small-btn {
width: 50px;
height: 25px;
}
.medium-btn {
width: 70px;
height: 30px;
}
.big-btn {
width: 90px;
height: 40px;
}
<div class="button big-btn">This is a big button</div>
<div class="button medium-btn">This is a medium button</div>
<div class="button small-btn">This is a small button</div>
jsFiddle example
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.
answered Jul 27, 2012 at 14:07
Anders ArpiAnders Arpi
8,2273 gold badges33 silver badges49 bronze badges
3
If you want to call a different size for the button inline, you would probably do it like this:
<div class="button" style="width:60px;height:100px;">This is a button</div>
Or, a better way to have different sizes (say there will be 3 standard sizes for the button) would be to have classes just for size.
For example, you would call your button like this:
<div class="button small">This is a button</div>
And in your CSS
.button.small { width: 60px; height: 100px; }
and just create classes for each size you wish to have. That way you still have the perks of using a stylesheet in case say, you want to change the size of all the small buttons at once.
answered Jul 27, 2012 at 14:10
1
Another alternative is that you are allowed to have multiple classes in a tag. Consider:
<div class="button big">This is a big button</div>
<div class="button small">This is a small button</div>
And the CSS:
.button {
/* all your common button styles */
}
.big {
height: 60px;
width: 100px;
}
.small {
height: 40px;
width: 70px;
}
and so on.
answered Jul 27, 2012 at 14:12
cobaltduckcobaltduck
1,5985 gold badges25 silver badges51 bronze badges
3
Use inline styles:
<div class="button" style="width:60px;height:100px;">This is a button</div>
Fiddle
bugwheels94
30k3 gold badges37 silver badges60 bronze badges
answered Jul 27, 2012 at 14:06
TurnipTurnip
35.4k15 gold badges88 silver badges109 bronze badges
1
try this one out resizeable button
<button type="submit me" style="height: 25px; width: 100px">submit me</button>
answered Aug 7, 2014 at 8:35
3
Тег <button> используется для создания интерактивных кнопок на веб-странице. В отличие от одинарного тега <input> (с атрибутом type=”button”), при помощи которого также можно создавать кнопки, содержимым тега <button> может быть как текст, так и изображение.
Если вы хотите создать кнопку в HTML форме, используйте элемент <input>, так как браузеры по-разному отображают содержимое тега <button>.
Содержимое тега пишется между открывающим <button> и закрывающим </button> тегами.
Пример
<!DOCTYPE html>
<html>
<head>
<title>Заголовок документа</title>
</head>
<body>
<h1>Вот наша кнопка..</h1>
<button type="button">Нажать</button>
</body>
</html>
Результат
К тегу <button> можно применять CSS стили для изменения внешнего вида кнопки, ее размера, цвета, шрифта текста и т.д.
Пример
<!DOCTYPE html>
<html>
<head>
<title>Заголовок документа</title>
</head>
<body>
Обычная кнопка
<button type="button">Добавить в корзину</button>
<hr />
Кнопка с красным текстом
<button type="button" style="color: red;"><b>Книга HTML</b></button>
<hr />
Кнопка с увеличенным размером шрифта
<button type="button" style="font: bold 14px Arial;">Загрузить книгу </button><br />
</body>
</html>
Результат
У тега <button> нет обязательных атрибутов, однако мы рекомендуем всегда использовать атрибут type=”button”, если тег используется в качестве обычной кнопки.
Тег <button> поддерживает глобальные атрибуты и атрибуты событий.
Узнайте, как стиль кнопок с помощью CSS.
Основные стили кнопок
Пример
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
Цвета кнопок
Используйте свойство background-color
для изменения цвета фона кнопки:
Пример
.button1 {background-color: #4CAF50;} /* Green */
.button2
{background-color: #008CBA;} /* Blue */
.button3 {background-color:
#f44336;} /* Red */
.button4 {background-color: #e7e7e7; color: black;} /* Gray */
.button5
{background-color: #555555;} /* Black */
Размеры кнопок
Используйте свойство font-size
для изменения размера шрифта кнопки:
Пример
.button1 {font-size: 10px;}
.button2 {font-size: 12px;}
.button3
{font-size: 16px;}
.button4 {font-size: 20px;}
.button5 {font-size: 24px;}
Используйте свойство padding
для изменения заполнения кнопки:
Пример
.button1 {padding: 10px
24px;}
.button2 {padding: 12px 28px;}
.button3 {padding: 14px 40px;}
.button4 {padding: 32px 16px;}
.button5 {padding: 16px;}
Закругленные кнопки
Используйте свойство border-radius
для добавления скругленных углов к кнопке:
Пример
.button1 {border-radius: 2px;}
.button2 {border-radius: 4px;}
.button3
{border-radius: 8px;}
.button4 {border-radius: 12px;}
.button5 {border-radius: 50%;}
Цветные границы кнопок
Используйте свойство border
, чтобы добавить цветную рамку к кнопке:
Пример
.button1 {
background-color: white;
color: black;
border: 2px solid #4CAF50; /* Green */
}
…
Наведите кнопки
Используйте селектор :hover
для изменения стиля кнопки при наведении на нее указателя мыши.
Совет: Используйте свойство transition-duration
для определения скорости эффекта «Hover»:
Пример
.button {
-webkit-transition-duration: 0.4s; /* Safari */
transition-duration: 0.4s;
}
.button:hover {
background-color: #4CAF50; /* Green */
color: white;
}
…
Кнопки теней
Use the box-shadow
property to add shadows to a button:
Пример
.button1 {
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0
rgba(0,0,0,0.19);
}
.button2:hover {
box-shadow: 0 12px
16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}
Отключенные кнопки
Используйте свойство opacity
для добавления прозрачности к кнопке (создает «отключенный» вид).
Совет: Вы также можете добавить свойство cursor
со значением «not-allowed», которое будет отображать «нет парковки знак» при наведении указателя мыши на кнопку:
Пример
.disabled {
opacity: 0.6;
cursor: not-allowed;
}
Ширина кнопки
По умолчанию размер кнопки определяется по ее текстовому содержимому (так же широко, как и ее содержимое). Используйте свойство width
для изменения ширины кнопки:
Пример
.button1 {width: 250px;}
.button2 {width: 50%;}
.button3 {width:
100%;}
Группы кнопок
Удалите поля и добавьте float:left
к каждой кнопке, чтобы создать группу кнопок:
Пример
.button {
float: left;
}
Группа кнопок на границе
Используйте свойство border
для создания группы кнопок с рамками:
Пример
.button {
float: left;
border: 1px
solid green;
}
Вертикальная группа кнопок
Используйте display:block
вместо float:left
для группирования кнопок ниже друг друга, вместо того, чтобы бок о бок:
Пример
.button {
display: block;
}
Кнопка на картинке
Анимированные кнопки
Пример
Добавить стрелку на наведении:
Пример
Добавить «нажатия» эффект на кнопку:
Пример
Исчезать при наведении:
Пример
Добавить эффект «рябь» при щелчке:
The <button>
HTML element is an interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it then performs an action, such as submitting a form or opening a dialog.
By default, HTML buttons are presented in a style resembling the platform the user agent runs on, but you can change buttons’ appearance with CSS.
Try it
Attributes
This element’s attributes include the global attributes.
autofocus
-
This Boolean attribute specifies that the button should have input focus when the page loads. Only one element in a document can have this attribute.
autocomplete
Non-standard
-
This attribute on a
<button>
is nonstandard and Firefox-specific. Unlike other browsers, Firefox persists the dynamic disabled state of a<button>
across page loads. Settingautocomplete="off"
on the button disables this feature; see bug 654072. disabled
-
This Boolean attribute prevents the user from interacting with the button: it cannot be pressed or focused.
Firefox, unlike other browsers, persists the dynamic disabled state of a
<button>
across page loads. Use theautocomplete
attribute to control this feature. form
-
The
<form>
element to associate the button with (its form owner). The value of this attribute must be theid
of a<form>
in the same document. (If this attribute is not set, the<button>
is associated with its ancestor<form>
element, if any.)This attribute lets you associate
<button>
elements to<form>
s anywhere in the document, not just inside a<form>
. It can also override an ancestor<form>
element. formaction
-
The URL that processes the information submitted by the button. Overrides the
action
attribute of the button’s form owner. Does nothing if there is no form owner. formenctype
-
If the button is a submit button (it’s inside/associated with a
<form>
and doesn’t havetype="button"
), specifies how to encode the form data that is submitted. Possible values:application/x-www-form-urlencoded
: The default if the attribute is not used.multipart/form-data
: Used to submit<input>
elements with theirtype
attributes set tofile
.text/plain
: Specified as a debugging aid; shouldn’t be used for real form submission.
If this attribute is specified, it overrides the
enctype
attribute of the button’s form owner. formmethod
-
If the button is a submit button (it’s inside/associated with a
<form>
and doesn’t havetype="button"
), this attribute specifies the HTTP method used to submit the form. Possible values:post
: The data from the form are included in the body of the HTTP request when sent to the server. Use when the form contains information that shouldn’t be public, like login credentials.get
: The form data are appended to the form’saction
URL, with a?
as a separator, and the resulting URL is sent to the server. Use this method when the form has no side effects, like search forms.
If specified, this attribute overrides the
method
attribute of the button’s form owner. formnovalidate
-
If the button is a submit button, this Boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the
novalidate
attribute of the button’s form owner.This attribute is also available on
<input type="image">
and<input type="submit">
elements. formtarget
-
If the button is a submit button, this attribute is an author-defined name or standardized, underscore-prefixed keyword indicating where to display the response from submitting the form. This is the
name
of, or keyword for, a browsing context (a tab, window, or<iframe>
). If this attribute is specified, it overrides thetarget
attribute of the button’s form owner. The following keywords have special meanings:_self
: Load the response into the same browsing context as the current one. This is the default if the attribute is not specified._blank
: Load the response into a new unnamed browsing context — usually a new tab or window, depending on the user’s browser settings._parent
: Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as_self
._top
: Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as_self
.
name
-
The name of the button, submitted as a pair with the button’s
value
as part of the form data, when that button is used to submit the form. type
-
The default behavior of the button. Possible values are:
submit
: The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with a<form>
, or if the attribute is an empty or invalid value.reset
: The button resets all the controls to their initial values, like <input type=»reset»>. (This behavior tends to annoy users.)button
: The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the element’s events, which are triggered when the events occur.
value
-
Defines the value associated with the button’s
name
when it’s submitted with the form data. This value is passed to the server in params when the form is submitted using this button.
Notes
A submit button with the attribute formaction
set, but without an associated form does nothing. You have to set a form owner, either by wrapping it in a <form>
or set the attribute form
to the id of the form.
<button>
elements are much easier to style than <input>
elements. You can add inner HTML content (think <i>
, <br>
, or even <img>
), and use ::after
and ::before
pseudo-elements for complex rendering.
If your buttons are not for submitting form data to a server, be sure to set their type
attribute to button
. Otherwise they will try to submit form data and to load the (nonexistent) response, possibly destroying the current state of the document.
While <button type="button">
has no default behavior, event handlers can be scripted to trigger behaviors. An activated button can perform programmable actions using JavaScript, such as removing an item from a list.
Example
<button name="button">Press me</button>
Accessibility concerns
Icon buttons
Buttons that only show an icon to represent do not have an accessible name. Accessible names provide information for assistive technology, such as screen readers, to access when they parse the document and generate an accessibility tree. Assistive technology then uses the accessibility tree to navigate and manipulate page content.
To give an icon button an accessible name, put text in the <button>
element that concisely describes the button’s functionality.
Example
<button name="favorite">
<svg aria-hidden="true" viewBox="0 0 10 10">
<path d="M7 9L5 8 3 9V6L1 4h3l1-3 1 3h3L7 6z" />
</svg>
Add to favorites
</button>
If you want to visually hide the button’s text, an accessible way to do so is to use a combination of CSS properties to remove it visually from the screen, but keep it parsable by assistive technology.
However, it is worth noting that leaving the button text visually apparent can aid people who may not be familiar with the icon’s meaning or understand the button’s purpose. This is especially relevant for people who are not technologically sophisticated, or who may have different cultural interpretations for the icon the button uses.
- What is an accessible name? | The Paciello Group
- MDN Understanding WCAG, Guideline 4.1 explanations
- Understanding Success Criterion 4.1.2 | W3C Understanding WCAG 2.0
Size and Proximity
Size
Interactive elements such as buttons should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44×44 CSS pixels is recommended.
- Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1
- Target Size and 2.5.5 | Adrian Roselli
- Quick test: Large touch targets — The A11Y Project
Proximity
Large amounts of interactive content — including buttons — placed in close visual proximity to each other should have space separating them. This spacing is beneficial for people who are experiencing motor control issues, who may accidentally activate the wrong interactive content.
Spacing may be created using CSS properties such as margin
.
- Hand tremors and the giant-button-problem — Axess Lab
ARIA state information
To describe the state of a button the correct ARIA attribute to use is aria-pressed
and not aria-checked
or aria-selected
. To find out more read the information about the ARIA button role.
Firefox
Firefox will add a small dotted border on a focused button. This border is declared through CSS in the browser stylesheet, but you can override it to add your own focused style using button::-moz-focus-inner { }
.
If overridden, it is important to ensure that the state change when focus is moved to the button is high enough that people experiencing low vision conditions will be able to perceive it.
Color contrast ratio is determined by comparing the luminosity of the button text and background color values compared to the background the button is placed on. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for large text. (Large text is defined as 18.66px and bold
or larger, or 24px or larger.)
- WebAIM: Color Contrast Checker
- MDN Understanding WCAG, Guideline 1.4 explanations
- Understanding Success Criterion 1.4.3 | W3C Understanding WCAG 2.0
Clicking and focus
Whether clicking on a <button>
or <input>
button types causes it to (by default) become focused varies by browser and OS. Most browsers do give focus to a button being clicked, but Safari does not, by design.
Technical summary
Content categories |
Flow content, phrasing content, Interactive content, listed, labelable, and submittable form-associated element, palpable content. |
---|---|
Permitted content |
Phrasing content but there must be no Interactive content |
Tag omission | None, both the starting and ending tag are mandatory. |
Permitted parents |
Any element that accepts phrasing content. |
Implicit ARIA role | button |
Permitted ARIA roles |
checkbox , combobox ,link , menuitem ,menuitemcheckbox ,menuitemradio , option ,radio , switch ,tab
|
DOM interface | HTMLButtonElement |
Specifications
Specification |
---|
HTML Standard # the-button-element |
Browser compatibility
BCD tables only load in the browser
Кнопки являются одним из самых понятных и интуитивных элементов интерфейса. По их виду сразу становится понятно, что единственное действие, которое с ними можно производить — это нажимать на них. За счёт этой особенности кнопки часто применяются в формах, особенно при их отправке и очистке.
Кнопку на веб-странице можно создать двумя способами — с помощью элемента <input> или <button>.
Рассмотрим вначале добавление кнопки через <input> и его синтаксис.
<input type="button" атрибуты>
Атрибуты кнопки перечислены в табл. 1.
Атрибут | Описание |
---|---|
name | Имя кнопки; предназначено для того, чтобы обработчик формы мог его идентифицировать. |
value | Значение кнопки и одновременно надпись на ней. |
Создание кнопки показано в примере 1.
Пример 1. Добавление кнопки
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Кнопка</title>
</head>
<body>
<form>
<p><input type=»button» value=» Нажми меня нежно «></p>
</form>
</body>
</html>
Пробелы в надписи на кнопке, в отличие от обычного текста в HTML, учитываются, поэтому можно ставить любое количество пробелов, которые в итоге влияют на ширину кнопки. Результат примера показан на рис. 1.
Рис. 1. Вид кнопки
Второй способ создания кнопки основан на использовании элемента <button>. Он по своему действию напоминает результат, получаемый с помощью <input>. Но в отличие от него предлагает расширенные возможности по созданию кнопок. Например, на подобной кнопке можно размещать любые элементы HTML, включая изображения и таблицы. На рис. 2 показаны разные виды кнопок, полученные с помощью <button>.
Рис. 2. Кнопки, созданные с помощью <button>
Синтаксис создания такой кнопки следующий.
<button атрибуты>Надпись на кнопке</button>
Атрибуты перечислены в табл. 1, но в отличие от кнопки <input> атрибут value определяет только отправляемое на сервер значение, а не надпись на кнопке. Если требуется вывести на кнопке изображение, то элемент <img> добавляется внутрь <button>, как показано в примере 2.
Пример 2. Рисунок на кнопке
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Кнопка</title>
</head>
<body>
<form>
<p><button>Кнопка с текстом</button>
<button>
<img src=»image/umbrella.gif» alt=»» style=»vertical-align:middle»>
Кнопка с рисунком
</button></p>
</form>
</body>
</html>
В данном примере показано создание обычной кнопки с текстом, а также кнопки с одновременным использованием текста и рисунка. Размер кнопки зависит от содержимого контейнера <button>, но пробелы игнорируются, поэтому простым увеличением их количества, как в случае использования <input>, ширину кнопки изменить не удастся.
Кнопка Submit
Для отправки данных на сервер предназначена специальная кнопка Submit. Её вид ничем не отличается от обычных кнопок, но при нажатии на нее происходит выполнение серверной программы, указанной атрибутом action элемента <form>. Эта программа, называемая еще обработчиком формы, получает данные введённые пользователем в полях формы, производит с ними необходимые манипуляции, после чего возвращает результат в виде HTML-документа. Что именно делает обработчик, зависит от автора сайта, например, подобная технология применяется при создании опросов, форумов, тестов и многих других вещей.
Синтаксис создания кнопки Submit зависит от используемого элемента <input> или <button>.
<input type="submit" атрибуты>
<button type="submit">Надпись на кнопке</button>
Атрибуты те же, что и у рядовых кнопок (пример 3).
Пример 3. Отправка данных на сервер
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Кнопка</title>
</head>
<body>
<form>
<p><input name=»login»></p>
<p><input type=»submit»></p>
</form>
</body>
</html>
Атрибут name для этого типа кнопки можно не писать. Если не указать значение value, то браузер самостоятельно добавит текст, он различается в зависимости от браузера. Так, Firefox пишет «Отправить запрос», IE — «Подача запроса», Opera и Chrome — «Отправить». Сам текст надписи никак на функционал кнопки не влияет.
Кнопка Reset
При нажатии на кнопку Reset данные формы возвращаются в первоначальное значение. Как правило, эту кнопку применяют для очистки введённой в полях формы информации. Для больших форм от использования кнопки Reset лучше вообще отказаться, чтобы по ошибке на неё не нажать, ведь тогда придётся заполнять форму заново.
Синтаксис создания указанной кнопки прост и похож на другие кнопки.
<input type="reset" атрибуты>
<button type="reset">Надпись на кнопке</button>
В примере 4 показана форма с одним текстовым полем, которое уже содержит предварительно введённый текст с помощью атрибута value элемента <input>. После изменения текста и нажатия на кнопку «Очистить», значение поля будет восстановлено и в нём снова появится надпись «Введите текст».
Пример 4. Кнопка для очистки формы
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Кнопка</title>
</head>
<body>
<form>
<p><input value=»Введите текст»></p>
<p><input type=»submit» value=»Отправить»>
<input type=»reset» value=»Очистить»></p>
</form>
</body>
</html>
Значение кнопки Reset никогда не пересылается на сервер. Если надпись на кнопке не писать, иными словами, не задавать атрибут value, на кнопке по умолчанию будет добавлен текст «Очистить».
Цветные кнопки
Вид и цвет кнопок зависит от операционной системы и браузера. Тем не менее можно изменить цвет кнопок по своему усмотрению, воспользовавшись стилями. Для этого требуется только добавить к кнопке свойство background, как показано в примере 5. Дополнительно можно поменять цвет текста и другие параметры. Помните про одну особенность — как только вы меняете цвет фона, кнопка становится приподнятой, поэтому для «плоских» кнопок надо добавить ещё рамку, пусть даже прозрачную.
Пример 5. Вид кнопок
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Кнопка</title>
<style>
.btn {
background: #5d8f76; /* Цвет фона */
color: #fff; /* Цвет текста */
padding: 7px 12px; /* Поля */
margin-bottom: 1em; /* Отступ снизу */
}
.btn:hover {
background: #1e6550; /* Цвет фона при наведении курсора */
}
.btn-flat {
border: 1px transparent; /* Прозрачная рамка */
}
.btn-round {
border-radius: 20px; /* Радиус скругления */
}
</style>
</head>
<body>
<form>
<p><input type=»button» value=»Исходная кнопка»>
<input type=»button» class=»btn» value=»Цветная кнопка»>
<input type=»button» class=»btn btn-flat» value=»Плоская кнопка»>
<input type=»button» class=»btn btn-flat btn-round» value=»Кнопка со скруглёнными уголками»></p>
</form>
</body>
</html>
Результат данного примера показан на рис. 3.
Рис. 3. Изменение вида кнопок
См. также
Последнее изменение: 11.03.2020
Статья, в которой познакомимся с процессом создания кнопок с помощью 3 или 4 версии фреймворка Bootstrap. Кроме этого рассмотрим плагин Bootstrap и научимся использовать его методы на практике.
Дефолтные кнопки
Кнопки — это один из самых распространённых элементов в дизайне сайтов и приложений. В большинстве случаев кнопки применяются для того, чтобы привлечь внимание посетителя сайта к действиям, которые они выполняют. Кнопки используются в HTML формах, диалоговых окнах, меню и во многих других местах веб-страниц.
Для оформления элемента в виде кнопки обычно используется <button>
, а также ссылки <a href
.
Хорошей практикой является использование ссылок <a href
для создания переходов между страницами, а <button>
— для выполнения различных действий на странице.
Создание дефолтной Bootstrap кнопки осуществляется посредством добавления к тегу базового класса btn
и класса с темой (например, btn-primary
).
<-- Bootstrap v4 и v5 -->
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-secondary">Secondary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-light">Light</button>
<button type="button" class="btn btn-dark">Dark</button>
<button type="button" class="btn btn-link">Link</button>
В Bootstrap 3 нет темы secondary, light и dark, но есть default.
Кнопки Bootstrap v3
Outline кнопки (только Bootstrap ?пеж4)
Создание бутстрап кнопки с контуром (без фона) необходимо добавить к элементы классы btn
и btn-outline-*
:
<button type="button" class="btn btn-outline-primary">Primary</button>
<button type="button" class="btn btn-outline-secondary">Secondary</button>
<button type="button" class="btn btn-outline-success">Success</button>
<button type="button" class="btn btn-outline-danger">Danger</button>
<button type="button" class="btn btn-outline-warning">Warning</button>
<button type="button" class="btn btn-outline-info">Info</button>
<button type="button" class="btn btn-outline-light">Light</button>
<button type="button" class="btn btn-outline-dark">Dark</button>
Изменение размера кнопки
Для увеличения или уменьшения размера кнопки, к ней нужно дополнительно добавить класс btn-{size}. Вместо {size} необходимо указать lg, sm или xs (только в Bootstrap 3).
Класс btn-lg предназначен для создания большой кнопки, sm — маленькой и xs — очень маленькой.
<!-- Bootstrap 3 --> <!-- Большая кнопка --> <button type="button" class="btn btn-default btn-lg">Текст кнопки</button> <!-- Маленькая кнопка --> <button type="button" class="btn btn-default btn-sm">Текст кнопки</button> <!-- Очень маленькая кнопка --> <button type="button" class="btn btn-default btn-xs">Текст кнопки</button>
<!-- Bootstrap 4 --> <!-- Большие кнопки --> <button type="button" class="btn btn-primary btn-lg">Текст кнопки</button> <button type="button" class="btn btn-secondary btn-lg">Текст кнопки</button> <!-- Маленькие кнопки --> <button type="button" class="btn btn-primary btn-sm">Текст кнопки</button> <button type="button" class="btn btn-secondary btn-sm">Текст кнопки</button>
Кнопка, занимающая всю ширину родительского элемента
Создание кнопки с шириной равной ширине родительского элемента осуществляется с помощью класса btn-block.
<!-- Bootstrap 3 --> <button type="button" class="btn btn-warning btn-lg btn-block">Текст кнопки</button> <button type="button" class="btn btn-primary btn btn-block">Текст кнопки</button> <button type="button" class="btn btn-success btn-sm btn-block">Текст кнопки</button> <button type="button" class="btn btn-danger btn-xs btn-block">Текст кнопки</button>
<!-- Bootstrap 4 --> <button type="button" class="btn btn-primary btn-lg btn-block">Текст кнопки</button> <button type="button" class="btn btn-secondary btn-block">Текст кнопки</button> <button type="button" class="btn btn-success btn-sm btn-block">Текст кнопки</button>
Активное состояние кнопки
Если необходимо отображать кнопку нажатой (с более тёмным фоном и рамкой), то к ней необходимо добавить класс active.
Для поддержки вспомогательных технологий к кнопке нужно добавить атрибут aria-pressed=»true».
<!-- Bootstrap 3 --> <a href="#" class="btn btn-primary active" role="button" aria-pressed="true">Текст кнопки</a>
<!-- Bootstrap 4 --> <a href="#" class="btn btn-primary active" role="button" aria-pressed="true">Текст кнопки</a>
Неактивное состояние кнопки
Если необходимо отключить возможность нажатия на кнопку, то её необходимо перевести в неактивное состояние.
Для элемента button это действие осуществляется посредством добавления к нему атрибута disabled.
<!-- Bootstrap 3 --> <button type="button" class="btn btn-primary" disabled>Текст кнопки</button>
<!-- Bootstrap 4 --> <button type="button" class="btn btn-primary" disabled>Текст кнопки</button>
Для отключения функциональности кнопки, созданной с помощью элемента a, необходимо выполнить немного другое действие, а именно добавить к ней класс disabled.
Класс disabled отключает возможность клика по кнопке посредством установки ей (элементу a) CSS-свойства pointer-events со значением none.
Для обеспечения поддержки вспомогательных технологий, таких как программ чтения с экрана, к кнопке (элементу a) необходимо добавить атрибут aria-disabled = «true».
<!-- Bootstrap 3 --> <a href="#" class="btn btn-primary disabled" tabindex="-1" role="button" aria-disabled="true">Текст кнопки</a>
<!-- Bootstrap 4 --> <a href="#" class="btn btn-primary disabled" tabindex="-1" role="button" aria-disabled="true">Текст кнопки</a>
Плагин Buttons
Компонент «Buttons» включает в себя не только CSS, но JavaScript. Данный код (buttons.js) добавляет на страницу функционал, предназначенный для управления состоянием кнопок, как отдельных, так и находящихся в группах.
Использование кнопки в качестве переключателя
Для создания кнопки-переключателя добавьте к ней атрибут data-toggle=»button». После этого при нажатии на кнопку она будет переключаться из обычного состояния в активное и наоборот.
Если кнопка изначально должна находиться в активном состоянии, то к ней необходимо добавить класс active и aria-pressed=»true».
<!-- Bootstrap 3 --> <button type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Кнопка-переключатель </button> <a href="#" class="btn btn-danger" data-toggle="button" aria-pressed="false" role="button"> Кнопка-переключатель </a>
<!-- Bootstrap 4 --> <button type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off"> Кнопка-переключатель </button> <a href="#" class="btn btn-danger" data-toggle="button" aria-pressed="false" role="button"> Кнопка-переключатель </a>
Checkbox и radio кнопки
CSS-стили Buttons можно применить и к другим HTML элементам, таким как к label, чтобы создать checkbox или radio кнопки.
<!-- Bootstrap 3 --> <!-- Checkbox --> <div class="btn-group" data-toggle="buttons"> <label class="btn btn-success active"> <input type="checkbox" checked autocomplete="off"> Показывать панель инструментов </label> </div> <!-- Radio buttons --> <div class="btn-group" data-toggle="buttons"> <label class="btn btn-warning active"> <input type="radio" name="options" id="option1" autocomplete="off" checked> Вариант 1 </label> <label class="btn btn-warning"> <input type="radio" name="options" id="option2" autocomplete="off"> Вариант 2 </label> <label class="btn btn-warning"> <input type="radio" name="options" id="option3" autocomplete="off"> Вариант 3 </label> </div>
<!-- Bootstrap 4 --> <!-- Checkbox --> <div class="btn-group-toggle" data-toggle="buttons"> <label class="btn btn-success active"> <input type="checkbox" checked autocomplete="off"> Показывать панель инструментов </label> </div> <!-- Radio buttons --> <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-warning active"> <input type="radio" name="options" id="option1" autocomplete="off" checked> Вариант 1 </label> <label class="btn btn-warning"> <input type="radio" name="options" id="option2" autocomplete="off"> Вариант 2 </label> <label class="btn btn-warning"> <input type="radio" name="options" id="option3" autocomplete="off"> Вариант 3 </label> </div>
Атрибут data-toggle=»buttons» предназначен для JavaScript. Он используется в его коде в качестве селектора для выбора элементов, к которым необходимо добавить поведение «переключения».
Состояние кнопок обновляется через событие click. Если необходимо использовать какой-то другой способ для обновления состояния checkbox или radio кнопок, то его нужно написать самостоятельно.
Класс btn-group-toggle (Bootstrap 4) предназначен для стилизации элементов input внутри группы.
Методы плагина Buttons
В Bootstrap 3 и 4 версии имеется метод $().button('toggle')
. Он предназначен для программного переключения состояния одной или нескольких кнопок.
Например, создадим 2 кнопки, и с помощью одной кнопки будем переключать состояние другой:
<!-- Bootstrap 4 --> <button type="button" id="toggle" class="btn btn-warning" autocomplete="off"> Выключено </button> <button type="button" id="toggleState" class="btn btn-secondary" autocomplete="off"> Переключить состояние </button> ... <script> $('#toggleState').on('click', function () { var toggleBtn = $('#toggle'); toggleBtn.button('toggle'); toggleBtn.hasClass('active') ? toggleBtn.text('Включено') : toggleBtn.text('Выключено'); }); </script>
В Bootstrap 3 кроме вышеприведённого метода имеются ещё 2:
- $().button(‘string’) — изменяет текст кнопки на значение, хранящееся в атрибуте data-string-text (имя атрибута составляется путём сложения строки data-, строкового значения, переданного в функцию button, например string и строки -text);
- $().button(‘reset’) — заменяет текст на изначальный.
Пример работы с методами $().button('complete')
и $().button('reset')
.
<!-- Bootstrap 3 --> <button type="button" id="download" data-complete-text="Скачать ещё раз" class="btn btn-primary" autocomplete="off"> Скачать </button> <button type="button" id="reset" class="btn btn-danger" autocomplete="off"> Сбросить </button> ... <script> $('#download').on('click', function () { $(this).button('complete'); }); $('#reset').on('click', function () { $('#download').button('reset'); }); </script>
Этот пример состоит из 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 --> <!-- 1 Способ --> <div class="text-center"> <button type="button" class="btn btn-primary">Текст кнопки</button> </div> <!-- 2 Способ --> <button type="button" class="btn btn-primary center-block">Текст кнопки</button>
<!-- Bootstrap 4 --> <!-- 1 Способ --> <div class="text-center"> <button type="button" class="btn btn-primary">Текст кнопки</button> </div> <!-- 2 Способ --> <button type="button" class="btn btn-primary d-block mx-auto">Текст кнопки</button>
Выравнивание кнопки по левому или правому краю
Способы выравнивания кнопки по левому или правому краю в Bootstrap 3 и 4 показаны в нижеприведенных примерах.
<!-- Bootstrap 3 --> <!-- 1 Способ --> <!-- Оборачивание кнопки с помощью элемента, например, div (который должен отображаться в документе как блочный) и добления к нему класса text-left или text-right --> <!-- Выравнивание кнопки по левому краю --> <div class="text-left"> <button type="button" class="btn btn-primary">Текст кнопки</button> </div> <!-- Выравнивание кнопки по правому краю --> <div class="text-right"> <button type="button" class="btn btn-primary">Текст кнопки</button> </div> <!-- 2 Способ --> <!-- Изменение типа отображения кнопки на блочный и добавления к ней CSS margin-left: auto или margin-right: auto. --> <!-- Выравнивание кнопки по левому краю --> <button type="button" class="btn btn-primary" style="display: block; margin-right: auto;">Текст кнопки</button> <!-- Выравнивание кнопки по правому краю --> <button type="button" class="btn btn-primary" style="display: block; margin-left: auto;">Текст кнопки</button>
<!-- Bootstrap 4 --> <!-- 1 Способ --> <!-- Оборачивание кнопки с помощью элемента, например, div (который должен отображаться в документе как блочный) и добления к нему класса text-left или text-right --> <!-- Выравнивание кнопки по левому краю --> <div class="text-left"> <button type="button" class="btn btn-primary">Текст кнопки</button> </div> <!-- Выравнивание кнопки по правому краю --> <div class="text-right"> <button type="button" class="btn btn-primary">Текст кнопки</button> </div> <!-- 2 Способ --> <!-- Изменение типа отображения кнопки на блочный и добавления к ней CSS margin-left: auto или margin-right: auto. В Bootstrap 4 это можно выполнить с помощью классов d-block, mr-auto и ml-auto --> <!-- Выравнивание кнопки по левому краю --> <button type="button" class="btn btn-primary d-block mr-auto">Текст кнопки</button> <!-- Выравнивание кнопки по правому краю --> <button type="button" class="btn btn-primary d-block ml-auto">Текст кнопки</button>
Как создать круглую кнопку
Для создания круглой кнопки необходимо установить с помощью CSS ей одинаковую ширину и высоту. Радиус скругления в этом случае нужно задать, равный половине ширины или высоты.
<style> /* CSS */ .btn-circle { width: 38px; height: 38px; border-radius: 19px; text-align: center; padding-left: 0; padding-right: 0; font-size: 16px; } </style> ... <!-- HTML --> <button type="button" class="btn btn-primary btn-circle"><i class="fas fa-map"></i></button>
Если необходимо содержимое кнопки расположить на нескольких строчках (например, иконку на одной, а текст на другой), то значение CSS свойства white-space необходимо сбросить или другими словами восстановить ему значение по умолчанию.
<style> /* CSS */ .btn-circle { width: 70px; height: 70px; border-radius: 35px; text-align: center; padding-left: 0; padding-right: 0; font-size: 16px; white-space: normal; /* восстанавливаем свойству значение по умолчанию */ } </style> ... <!-- HTML --> <button type="button" class="btn btn-primary btn-circle"><i class="fas fa-map"></i></button>
Как создать кнопку с иконкой
1 вариант.
<style> /* CSS */ .btn-rounded { border-radius: 19px; padding-top: 3px; padding-bottom: 3px; padding-left: 3px; } </style> ... <!-- HTML --> <button type="button" class="btn btn-primary btn-rounded"><i class="fas fa-map text-primary rounded-circle bg-white mr-1" style="padding: 7px 6px;"></i> Map</button>
2 вариант.
<style> /* CSS */ .btn-icon { padding-top: 0; padding-bottom: 0; } .btn > .icon { position: relative; left: -.75rem; display: inline-block; padding: .375rem .75rem; background: rgba(0, 0, 0, 0.15); border-radius: .25rem 0 0 .25rem; } </style> ... <!-- HTML --> <button type="button" class="btn btn-secondary btn-icon"> <span class="icon"><i class="fas fa-download"></i></span>Download </button>
3 вариант.
<!-- HTML --> <button type="button" class="btn btn-secondary"> Download <i class="fas fa-download"></i> </button>