<button>
The <button>
tag is used in HTML to create interactive buttons.
These buttons can be used to execute various actions, such as submitting a form, triggering JavaScript scripts, or making interface modifications.
Structure and syntax of the <button>
tag
Here is the basic structure of the <button>
tag:
<button>Button text or content</button>
You can add anything you want! Whether it's icons, bold text, italic text... Let your imagination run wild! 😉
Attributes
The <button>
tag supports several attributes to customize its behavior and style:
type
: Defines the behavior of the button. You can set one of these values:- button: A generic button with no default behavior;
- submit: Submits the form;
- reset: Resets the form fields.
disabled
: Disables the button, preventing any interaction with it.name
andvalue
: Used to transmit additional data when the form is submitted. They are often used together with an<input>
tag.autofocus
: Automatically sets the focus on the button when the page is loaded.
Usage example
Here is an example of buttons with different behaviors:
<form>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
<button type="button" onclick="alert('Hello!')">Click me</button>
</form>
In this example:
- The "Submit" button submits the form data.
- The "Reset" button resets the form fields to their default values.
- The "Click me" button displays an alert when clicked, thanks to the
onclick
attribute. Note that any JavaScript code can be used with this attribute.
Difference with the <input> tag
The <button>
tag is often compared to the <input>
tag with the type="button"
attribute.
However, these two tags are very different:
<button>
can contain rich content such as text, icons, or images, whereas<input>
can only contain text;- The
<button>
tag offers more flexibility in terms of styling with CSS.
Don't overlook this last point! 😬
Browser compatibility
The <button>
tag is supported by all modern browsers:
Browser | Compatibility |
---|---|
Google Chrome | Yes |
Mozilla Firefox | Yes |
Safari | Yes |
Microsoft Edge | Yes |
Internet Explorer | Yes |