Signup/Sign In
LAST UPDATED: AUGUST 5, 2021

How to center a button element vertically and horizontally with CSS?

The buttons can be aligned center horizontally or vertically using CSS. In this tutorial, we will learn about the properties to align the button vertically and horizontally.

Using flex properties

The flexbox properties can be used to align the button horizontally and vertically center. We can horizontally center the button element using the CSS align-items property along with the value center. While we can vertically center the button element using the CSS property justify-content along with the value center.

If we want to center a button element both horizontally and vertically then we have to specify both the CSS property justify-content and align-items along with the value center.

Example: Center align button vertically and horizontally

In this program, we have used flexbox properties to center align buttons both vertically and horizontally.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
	.container {
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  border: 2px solid blue;
	  height: 200px;
 }
    button {
	  padding: 10px;
	  font-size: 16px;
	  background: #d34567;
	}

</style>
</head>
<body>
   <h2 style="text-align:center">Center align the button horizontally and vertically </h2>
   <div class="container">
    <button>centered button </button>
   </div>

</body>
</html>

Output

Here is the output of the above program.

center button horizontally and vertically

Using CSS transform property

Other than flexbox property, we can also center align the button horizontally and vertically using a set of CSS properties. Add position: relative to the container class and position: absolute to the class containing the button. Now use left:50% and top:50% to position the button to the center of the container. along with it use transform: translate(-50%,-50%).

Example: Center the button horizontally and vertically

In this program, we have used the above properties to center the button horizontally and vertically.

Conclusion

In this tutorial, we have learned the ways to center the button horizontally and vertically using CSS. We can use flexbox property or position property to do so. It has been explained with examples.



About the author: