center button css
Code snippet for how to center button css with sample and detail explanation
Centering a button in CSS might seem complicated to some, especially if you’re just starting out with coding. Fortunately, it is actually pretty straightforward. This article aims to guide you step by step on how to center a button using CSS.
Code Snippet for Center Button in CSS
Here, we have a simple snippet of CSS that shows us how to center a button:
.button-wrapper {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 30px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
Code Explanation for Center Button in CSS
In the CSS code snippet above, we created two classes: .button-wrapper
and .button
.
The .button-wrapper
class is used as a container for the button. We set this container to display: flex;
, which turns the container into a flex container and lets us use the CSS Flexbox properties on the items inside it.
justify-content: center;
is a Flexbox property that aligns the container’s items along the horizontal line in the center of the container. align-items: center;
is another Flexbox property that centers the items along the vertical line.
The height: 100vh;
rule makes the container take up 100% of the viewport’s height, so that the button will be centered both vertically and horizontally.
The .button
class applies styles to the button itself, like background color, padding, font size, etc., to make it stand out and be easily clickable. The display: inline-block;
rule allows us to adjust the padding and margin of the button, and keeps it in line with other elements.
And voila! With these two classes, your button is now centered in the middle of the viewport. Remember, practice is key when it comes to coding. So, keep exploring and have fun with your CSS designs!