OneBite.Dev - Coding blog in a bite size

center a button in css

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

Centering a button in CSS can seem a little daunting at first, especially if you’re new to the world of web design. However, with a bit of know-how and the right technique, you’ll find that it’s a pretty straightforward task.

CSS Code to Center a Button

Below is the code snippet that can be used to center a button in CSS:

.button-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.btn {
  background-color: #4CAF50; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

In this HTML:

<div class="button-container">
    <button class="btn">Click me</button>
</div>

Explanation for CSS Code to Center a Button

Let’s break down the CSS code we’ve used for better understanding:

The “.button-container” class represents the container, and its display property is set to ‘flex’. Flexbox is a CSS layout module that enables complex layouts. Setting the display to ‘flex’ gives it the property to align items vertically and horizontally at the center.

The ‘justify-content: center;’ line is a property that aligns the button horizontally at the center.

The ‘align-items: center;’ line ensures that the button is centered vertically.

The padding property gives some space around the text inside the button, making it easy for people to tap or click the button.

background-color: #4CAF50; /* Green */ sets the background color of the button, and ‘color: white;’ sets the text color of the button to white.

text-align: center; makes the text in the button centered.

display: inline-block; allows the width and height to be set for the button.

And font-size: 16px; sets the size of the font in the button.

That concludes the steps to center a button using CSS. By modifying the size and colors, you can easily customize this and make your button fit seamlessly into the rest of your web design. Happy designing!

css