How to Create Button in Bootstrap: Simple Guide
To create a button in Bootstrap, use the
<button> element with the class btn and a style class like btn-primary. This adds Bootstrap's styling and behavior to your button easily.Syntax
Bootstrap buttons use the <button> tag with the base class btn. You add a style class like btn-primary for color and appearance. Optionally, you can add size classes like btn-lg for large buttons.
html
<button type="button" class="btn btn-primary">Button</button>
Output
A blue styled button labeled 'Button' appears.
Example
This example shows a simple Bootstrap button with primary styling and a click alert.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap Button Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <button type="button" class="btn btn-primary" onclick="alert('Button clicked!')">Click Me</button> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> </body> </html>
Output
A blue button labeled 'Click Me' appears. Clicking it shows an alert 'Button clicked!'.
Common Pitfalls
Common mistakes include forgetting the btn base class, which means no Bootstrap styles apply. Another is missing the Bootstrap CSS link, so buttons look plain. Also, using type="submit" unintentionally can submit forms when you only want a clickable button.
html
<!-- Wrong: Missing btn class --> <button type="button" class="btn-primary">No Style</button> <!-- Right: Include btn class --> <button type="button" class="btn btn-primary">Styled Button</button>
Output
First button looks like a normal button with no color. Second button is styled blue.
Quick Reference
| Class | Description |
|---|---|
| btn | Base class for all Bootstrap buttons |
| btn-primary | Blue primary button style |
| btn-secondary | Gray secondary button style |
| btn-success | Green success button style |
| btn-danger | Red danger button style |
| btn-warning | Yellow warning button style |
| btn-info | Light blue info button style |
| btn-light | Light background button style |
| btn-dark | Dark background button style |
| btn-link | Button styled as a link |
| btn-lg | Large button size |
| btn-sm | Small button size |
Key Takeaways
Always include the base class 'btn' to apply Bootstrap button styles.
Use style classes like 'btn-primary' to change button colors.
Link Bootstrap CSS in your HTML to see the styled buttons.
Avoid missing 'btn' class or Bootstrap CSS to prevent plain buttons.
Use button 'type' attribute carefully to control form behavior.