HTML Buttons
What are HTML Buttons?
The HTML <button> element creates a clickable button. Buttons can contain text, images, or other HTML elements. Unlike buttons created with <input type="button">, the <button> element allows for more flexible content and styling.
Basic Button
The simplest button with just text:
Example
<button>Click Me</button>
Button Types
The type attribute specifies the button's behavior:
1. Submit Button (Default)
Submits form data. If no type is specified, this is the default:
Example
<form action="#">
<input type="text" name="name" placeholder="Enter name">
<button type="submit">Submit</button>
</form>
2. Reset Button
Resets form fields to their initial values:
Example
<form action="#">
<input type="text" name="name" placeholder="Enter name" value="John">
<button type="reset">Reset</button>
</form>
3. Button Type
A generic button that doesn't submit or reset. Use with JavaScript:
Example
<button type="button" onclick="alert('Button clicked!')">Click Me</button>
Button Attributes
Common attributes for buttons:
Disabled Button
Example
<button disabled>Disabled Button</button>
<button>Enabled Button</button>
Button with Name and Value
Used when submitting forms:
Example
<form action="#">
<button type="submit" name="action" value="save">Save</button>
<button type="submit" name="action" value="delete">Delete</button>
</form>
Styling Buttons
Buttons can be styled with CSS:
Example
<style>
.styled-button {
background-color: #4b3190;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
.styled-button:hover {
background-color: #fdbb30;
color: black;
}
.styled-button:active {
background-color: #333;
color: white;
}
</style>
<button class="styled-button">Styled Button</button>
Button vs Input Button
There's a difference between <button> and <input type="button">:
| Feature | <button> |
<input type="button"> |
|---|---|---|
| Content | Can contain HTML (text, images, etc.) | Text only (value attribute) |
| Styling | Easier to style with CSS | More limited styling |
| Form behavior | Type attribute required | Always type="button" |
Button with Images
Buttons can contain images and other HTML:
Example
<button type="button">
<img src="icon.png" alt="Icon" style="width: 20px; height: 20px;">
Click Me
</button>
<button type="button">
<strong>Bold</strong> and <em>italic</em> text
</button>
Best Practices
- Use type attribute: Always specify the type attribute
- Provide labels: Make button text clear and descriptive
- Consider accessibility: Use descriptive text for screen readers
- Style consistently: Maintain consistent button styling across your site
- Handle disabled state: Visually distinguish disabled buttons