To create a button in HTML, use the <button>
tag. This element generates a clickable button that can contain text and even other HTML elements such as icons or images.
Basic Syntax
<button type="button">Click Me!</button>
- The opening
<button>
tag starts the button. - The closing
</button>
tag ends the button. - The text between the tags (“Click Me!”) is the label shown on the button.
Tip: Always specify the
type
attribute (button
,submit
, orreset
) to define the button’s behavior, as browsers may set a different default if you omit it.
type="button"
is for a standard clickable button (default action is none).type="submit"
submits the nearest form.type="reset"
resets form data to its defaults.
Example: Basic Button Usage
<button type="button">Click Me!</button>
Example: Button with Icon or HTML Content
<button type="button">
<img src="icon.png" alt="" style="width:16px; vertical-align:middle;">
Save
</button>
You can include text, images, or inline HTML markup within a <button>
(unlike the <input type="button">
, which only supports text).
Event Handling
You can add event attributes like onclick
to make the button interactive with JavaScript:
<button type="button" onclick="alert('Button Clicked!')">
Click Me!
</button>
Common events: onclick
, onmouseover
, onmouseout
, onfocus
, onblur
.
Example: Buttons in a Form
<form>
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</form>
type="submit"
: submits the form.type="reset"
: resets the form’s fields.
Customizing and Styling Buttons
Buttons are easily styled using CSS:
<style> button { background-color: #1976d2; color: white; padding: 10px 20px; border: none; border-radius: 6px; font-size: 16px; cursor: pointer; } button:hover { background-color: #155a9b; } </style> <button type="button">Styled Button</button>
You can style hover effects, colors, padding, borders, and more.
Accessibility and Best Practices
- Use clear, descriptive labels for buttons.
- Specify the correct
type
. - Buttons can be disabled using the
disabled
attribute: xml<button type="button" disabled>Can't Click Me</button>