OneBite.Dev - Coding blog in a bite size

make button in css

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

Creating stylish and efficient buttons is critical for improving the user interface of any website. Achieving such buttons is possible through Cascading Style Sheets (CSS) and this article will guide you through the simple process of creating a button in CSS.

Code snippet for creating a button in CSS

CSS provides vast opportunities for tweaking and enhancing the basic HTML button. Below is a short example:

.button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}

Moreover, in the HTML file where you want the button to exist, you will have to apply this class to a button tag:

<button class="button">Click me</button>

Code Explanation for creating a button in CSS

This section breaks down the CSS code and explains what each line does - it’s a step-by-step tutorial on creating your CSS button.

Firstly, “.button” is the CSS class that we will be using to style our button. The elements within this class are what tell the browser how to display this particular HTML element.

  1. “background-color: #4CAF50;” sets the background color of the button.

  2. “border: none;” This property sets the border of the button. Here, it is set to none, meaning that the button will not have a border.

  3. “color: white;” specifies the color of the text on the button. In this case, the text color is set to white.

  4. “padding: 15px 32px;” sets the padding around the text on the button. This helps us control the button’s size.

  5. “text-align: center;” this property aligns the text to the center of the button.

  6. “text-decoration: none;” it removes any decoration that would ordinarily be around the text (like underlines).

  7. “display: inline-block;” by setting this, we make the button fit into the normal flow of the webpage while still retaining its block properties.

  8. “font-size: 16px;” this sets the font size of the text on the button.

  9. “margin: 4px 2px;” it creates space around the button.

  10. “cursor: pointer;” changes the cursor when you hover over the button, giving the user a visual cue that the text is clickable.

Finally, you have to apply this class to your HTML button using the class attribute. After styling with CSS, your button will have the desired style and functionality.

css