center buttons in css
Code snippet for how to center buttons in css with sample and detail explanation
CSS is a multifaceted tool that can be used to create aesthetically pleasing visuals on your website. One common task is centering buttons, and in this article, we’ll explain a step by step process on how to achieve this using CSS.
Code Snippet: Centering a Button in CSS
Below is a simple and effective CSS snippet to center a button:
<!DOCTYPE html>
<html>
<head>
<style>
.center {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 1px solid;
}
.center button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
</style>
</head>
<body>
<div class="center">
<button>Click me</button>
</div>
</body>
</html>
Code Explanation: Centering a Button in CSS
Now let’s breakdown what the code is doing:
-
The ‘center’ class is created, and we define it to have a display property of ‘flex’. This makes the container flexible and allows for easier alignment of child items.
-
The ‘justify-content:center;’ property aligns the button horizontally in the center of its container.
-
Similarly, the ‘align-items:center;’ property aligns the button vertically in the middle of its container.
-
The ‘height:200px;’ property gives a specific height to the container. This can be adjusted depending on your specific needs.
-
Border property is optional and it just adds a border to the div showing the exact area of the center div.
After setting up the parent container, we proceed to style the child item, our button.
-
The ‘.center button’ selector targets the button inside the ‘center’ div.
-
The ‘background-color: #4CAF50;’ gives the button a green background color.
-
The ‘color:white;’ property sets the color of the text inside the button to white.
-
The ‘padding: 15px 32px;’ adds space around the text in the button. The first value is the vertical padding, and the second is the horizontal padding.
-
The ‘text-align:center;’ ensures that the text is centered within the button.
-
The ‘display: inline-block;’ allows the button to sit inline with other elements but still have block properties.
-
Lastly, ‘font-size: 16px;’ Sets the font-size of the text inside the button.
Hence, by utilizing these properties, you are able to effectively center a button using CSS.