OneBite.Dev - Coding blog in a bite size

make a button in css

Code snippet for how to make a button in css with sample and detail explanation

Creating web elements with purely HTML can be efficient; however, enhancing these elements with CSS can turn them functional and make them look geeky. Today, we’ll walk you through a guide on how to create a beautiful and functional button using CSS, including discussions on the piece of code and its explanation.

Code snippet for Creating a Button

Below is the basic code snippet on how you can create a simple button using HTML and CSS:

<!DOCTYPE html>
<html>
<head>
    <style>
       .btn {
           background-color: #4CAF50; /* Green */
           border: none;
           color: white;
           padding: 15px 32px;
           text-align: center;
           text-decoration: none;
           display: inline-block;
           font-size: 16px;
           margin: 4px 2px;
           cursor: pointer;
       }
    </style>
</head>
<body>
    <button class="btn">Click Me!</button>
</body>
</html>

Code Explanation for Creating a Button

This tutorial focuses on explaining the CSS part of the code, as the HTML part is quite self-explanatory. In the above code snippet, we have defined a CSS class named ‘btn’.

  1. .btn: This is the name of the CSS class that we can apply to any HTML element. In this case, we are applying it to a button.

  2. background-color: #4CAF50;: The background color of the button is set to green.

  3. border: none;: We don’t want any border for our button, so we set the border property to ‘none’.

  4. color: white;: This sets the color of the text inside the button to white.

  5. padding: 15px 32px;: The padding property sets the space between the content of the button and its border or edge. The first value is for the top and bottom padding, and the second one is for the left and right padding.

  6. text-align: center;: This property aligns the text to the center of the button.

  7. text-decoration: none;: This removes any decoration like underlining, overlining, or strike-through from the text.

  8. display: inline-block;: This makes the button inline but it can have a width and height.

  9. font-size: 16px;: This sets the font size of the text inside the button.

  10. margin: 4px 2px;: Sets the outer space of the button. The first value is for the top and bottom margin, and the second one is for the left and right margin.

  11. cursor: pointer;: This changes the cursor to a hand icon when you hover over the button, indicating that it is clickable.

Lastly, we apply our CSS class to the button in the HTML (<button class="btn">Click Me!</button>). This makes the button inherit all properties defined in the ‘btn’ CSS class.

There you have it! You’ve just created a functional and appealing button using CSS. This button can be used in a variety of ways, such as submitting a form, opening a new link, and so on. Enjoy coding!

css