button
You can put text or images inside a button element. If the element is not disabled, the user can activate the button.
By default, the button element is used to submit form data. Modifying the type attribute can change this behavior.
Attributes (HTML 4)
- submit : the button submits the form it is associated with and sends the form data to the server. This is the default value.
- reset : the button resets the form it is associated with. This will set the containing fields to their initial values.
- button : the button has no default behavior. Useful to bind JavaScript click events
Additional attributes (HTML 5, candidate specification)
When this attribute is set to “true” the button will have input focused after the page loads, unless the user overrides it, for example by typing in a different control. Only one form-associated element in a document can have this attribute specified.
form
Specifies which form the button is associated with. The value of the attribute must be the id attribute of the form. If this attribute is not specified, the button must be a descendant of the form itself to be able to submit form data. This attribute enables you to place button elements anywhere within a document, not just as descendants of their form elements.
formaction
The URI of a program that processes the information from the form. When present, it will override the action attribute of the associated form.
formmethod
The HTTP method to send the form data. This can either be post or get . If specified, it will override the method attribute of the associated form. Possible values are:
- post : The data from the form is included in the body of the form and is sent to the server.
- get : The data from the form are appended to the form attribute URI, with a ‘?’ as a separator, and the resulting URI is sent to the server. Use this method when the form has no side-effects and contains only ASCII characters.
If the button is a submit button, this attribute specifies whether the form should be validated or not. It overrides the novalidate attribute of the form it belongs to.
formtarget
This attribute is a keyword, indicating where to display the response that is received after submitting the form. This can be one of the following:
- _self : load the response into the same context as the form itself. This is the default value.
- _blank : load the response into a new, unnamed context (Browser window)
- _parent : loads the response into the parent context. If there is no parent, it will behave the same as _self.
- _top : loads the response into the top-most context. This is the browsing context of an ancestor of the current context. If there is no parent, it will behave the same as _self.
All these attributes, except name , have default values and can be omitted.
Examples
This examples uses the <button> element to display a clickable button with out sending or reseting a form.
This example shows how to use a submit <button> to send a form. Read about the form element to get further information about how to use forms.
This example shows how to reset a form with use of <button="reset"> . Read about the form element to get further information about how to use forms.
Usage
The ending tag is mandatory. The button should have a descriptive text inside it, otherwise the button will be empty and the user won’t know what the button will do.
Please note that styling a submit button using the <button> element is easier than styling an input element with type submit .
Notes
Since the default for the type attribute is submit , the type can be omitted if no other type needs to be used. Historical browser versions may have different standard type values.
Firefox for Android, by default, sets a background-image gradient on all button elements. This can be disabled using background-image: none .
Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a button across page loads. Setting the value of the autocomplete attribute to off disables this feature. See Mozilla Bug #654072.
Clicking and focus
Whether clicking on a button causes it to (by default) become focused varies by browser and OS.
<button> — элемент кнопки
HTML-элемент <button> создаёт кликабельную кнопку, которая может быть использована в формах или в любом другом месте документа, который требует простой, стандартной кнопки. По умолчанию, кнопки HTML обычно представлены в стиле, аналогичном стилю хост-платформы, на которой работает user agent, но вы можете изменить внешний вид кнопки, используя CSS.
| Категории контента | Общий поток (en-US) , текстовый контент (en-US) , интерактивный контент (en-US) , listed (en-US) , labelable (en-US) , и submittable (en-US) form-associated (en-US) элемент, очевидный контент. |
|---|---|
| Допустимое содержимое | Текстовый контент (en-US) . |
| Пропуск тегов | Нет, открывающий и закрывающий теги обязательны. |
| Допустимые родители | Любой элемент с поддержкой текстового контента (en-US) . |
| Допустимые ARIA-роли | checkbox , link (en-US) , menuitem (en-US) , menuitemcheckbox (en-US) , menuitemradio (en-US) , radio (en-US) , switch (en-US) , tab (en-US) |
| DOM-интерфейс | HTMLButtonElement |
Атрибуты
Данный булевый атрибут позволяет указать, будет ли кнопка автоматически сфокусирована после загрузки страницы, до тех пор, пока пользователь не изменит фокус в ручную, например выбрав другой элемент. Только один связанный с формой элемент в документе может иметь данный атрибут.
Использование данного атрибута на элементе <button> не описано в стандарте и используется только в Firefox браузере. По умолчанию, в отличие от прочих браузеров, Firefox сохраняет назначенное динамически отключённое состояние для элемента <button> при последующих загрузках страницы. Установка для данного атрибута значения off отключает подобное поведение. Смотрите баг 654072.
Булевый атрибут, указывающий, что пользователь не может взаимодействовать с кнопкой. Если атрибут не установлен, то кнопка наследует его от элемента-контейнера, в котором она расположена, например от <fieldset> ; если отсутствует элемент-контейнер, с установленным атрибутом disabled, то кнопка доступна для взаимодействия.Firefox по умолчанию, в отличие от прочих браузеров, сохраняет назначенное динамически отключённое состояние для элемента <button> , даже при обновлении страницы. Чтобы изменить поведение браузера в этом случае, используйте атрибут autocomplete .
Атрибут form позволяет указать элемент <form> , с которым связана кнопка. Данный атрибут должен хранить значение id элемента <form> . Если данный атрибут не установлен, то элемент <button> будет связан с родительским элементом <form> , если последний существует.Атрибут работает независимо от расположения элементов в документе, поэтому он позволяет связать элемент <button> с формой, даже в случае, если <button> не является наследником элемента <form> .
Ссылка на обработчик формы. Если атрибут определён — он переопределит атрибут action у формы-родителя.
Если button имеет тип submit , то этот атрибут определяет тип контента, отправляемого на сервер. Возможные значения данного атрибута:
- application/x-www-form-urlencoded : значение по умолчанию, если атрибут не указан.
- multipart/form-data : следует использовать это значение, если форма содержит элемент <input> со значением атрибута type file .
- text/plain Если этот атрибут определён, он переопределяет атрибут enctype у формы-родителя.
Если button имеет тип submit , то этот атрибут определяет метод HTTP-запроса для отправки данных на сервер. Возможные варианты:
- post : данные формы включаются в тело сообщения и отправляются на сервер.
- get : данные формы отправляются на сервер в виде ссылки, состоящей из URI атрибута action и непосредственно данных, отделённых знаком ‘?’. Данные формы будут иметь вид ключ/значение и разделены амперсандом, например name=Name&id=35. Следует использовать этот метод только если нет побочных эффектов и данные формы содержат лишь ASCII-символы.Если этот атрибут определён, он переопределяет атрибут method у формы-родителя.
Булевый атрибут. Указывает, что данные формы не будут валидироваться при отправке.Если этот атрибут определён, он переопределяет атрибут novalidate у формы-родителя.
Если button имеет тип submit , этот атрибут является именем или ключевым словом,указывающим, где отображать ответ, полученный после отправки формы. This is a name of, or keyword for, a browsing context (for example, tab, window, or inline frame). If this attribute is specified, it overrides the target 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 value is the default if the attribute is not specified.
- _blank : Load the response into a new unnamed browsing context.
- _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 .
Название кнопки, которая отправляется вместе с данными формы.
Устанавливает тип кнопки. Достпуные значения:
- submit : Кнопка отправляет данные формы на сервер. Это значение по умолчанию, если атрибут не указан или если атрибут динамически изменен на пустое или недопустимое значение.
- reset : Кнопка сбрасывает все элементы управления к их начальным значениям. Удаляет данные, введенные в форму.
- button : Кнопка не имеет поведения по умолчанию. При этом на странице могут быть скрипты, активируемые при возникновении определённых событий на кнопке.
- menu : Кнопка открывает всплывающее меню, определяемое с помощью соответствующего <menu> элемента.
Начальное значение кнопки.
Пример
Clicking and focus
Whether clicking on a <button> causes it to (by default) become focused varies by browser and OS. The results for <input> of type=»button» and type=»submit» are the same.
HTML <button> Tag
Inside a <button> element you can put text (and tags like <i> , <b> , <strong> , <br> , <img> , etc.). That is not possible with a button created with the <input> element!
Tip: Always specify the type attribute for a <button> element, to tell browsers what type of button it is.
Tip: You can easily style buttons with CSS! Look at the examples below or visit our CSS Buttons tutorial.
Browser Support
| Element | |||||
|---|---|---|---|---|---|
| <button> | Yes | Yes | Yes | Yes | Yes |
Attributes
| Attribute | Value | Description |
|---|---|---|
| autofocus | autofocus | Specifies that a button should automatically get focus when the page loads |
| disabled | disabled | Specifies that a button should be disabled |
| form | form_id | Specifies which form the button belongs to |
| formaction | URL | Specifies where to send the form-data when a form is submitted. Only for type="submit" |
| formenctype | application/x-www-form-urlencoded multipart/form-data text/plain |
Specifies how form-data should be encoded before sending it to a server. Only for type="submit" |
| formmethod | get post |
Specifies how to send the form-data (which HTTP method to use). Only for type="submit" |
| formnovalidate | formnovalidate | Specifies that the form-data should not be validated on submission. Only for type="submit" |
| formtarget | _blank _self _parent _top framename |
Specifies where to display the response after submitting the form. Only for type="submit" |
| name | name | Specifies a name for the button |
| type | button reset submit |
Specifies the type of button |
| value | text | Specifies an initial value for the button |
Global Attributes
Event Attributes
The <button> tag also supports the Event Attributes in HTML.
More Examples
Example
Use CSS to style buttons:
<!DOCTYPE html>
<html>
<head>
<style>
.button <
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
>
Example
Use CSS to style buttons (with hover effect):
<!DOCTYPE html>
<html>
<head>
<style>
.button <
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
>
.button1 <
background-color: white;
color: black;
border: 2px solid #4CAF50;
>
.button1:hover <
background-color: #4CAF50;
color: white;
>
.button2 <
background-color: white;
color: black;
border: 2px solid #008CBA;
>
.button2:hover <
background-color: #008CBA;
color: white;
>
<button>: The Button element
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 a programmable 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
| Content categories | Flow content, phrasing content, Interactive content, listed, labelable, and submittableform-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 , link , menuitem , menuitemcheckbox , menuitemradio , option , radio , switch , tab |
| DOM interface | HTMLButtonElement |
Attributes
This element’s attributes include the global attributes.
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.
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. Setting autocomplete=»off» on the button disables this feature; see bug 654072.
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 the autocomplete attribute to control this feature.
The <form> element to associate the button with (its form owner). The value of this attribute must be the id 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.
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.
If the button is a submit button (it’s inside/associated with a <form> and doesn’t have type=»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 : Use to submit <input> elements with their type attributes set to file .
- 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.
If the button is a submit button (it’s inside/associated with a <form> and doesn’t have type=»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’s action 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.
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.
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 the target 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 .
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.
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.
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.
Example
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
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.
Size and Proximity
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.
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 .
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.)