html

How to Center a Button Using CSS Flexbox

In HTML, buttons are clickable elements used to perform a specific action. Using CSS, you can set the button’s position where you want to place it. For doing so, there are several techniques in CSS, one of them is flexbox. “flex” is used to set the position of the element according to its viewport.

This article will teach how to center a button using CSS Flexbox.

So, let’s begin!

How to Center Button Using CSS flexbox?

flex” is the value set for the display property of CSS. Depending on the viewport size, it sets content or elements accordingly. In CSS, the flex value creates equal space between elements to ensure they are arranged efficiently.

Syntax

In the above-given syntax, “flex” will be specified as the value of the “display” property.

So, let’s check out the example to centralize the button using flex.

Example

In the <body> of HTML, we will create an container with <div> class named “button” and inside it create a button using <button> tag:

In the CSS file, “.button” is used to access the class we have assigned to the <div>. To set the position of the added button in the center of the div, we will assign the value of the display property, justify-content, and align-items as “flex”, “center”, and “center”, respectively. Furthermore, we will set the height of the created div to “200px” and assign the value of border as “5px”, “solid” and “black”:

In the above-given code, “justify-content” is used for setting the button in the center of the div horizontally and “align-item” is used for setting the button in the center of the div vertically.

After implementing the above code, go to the HTML file and execute it to see the following outcome:

You can see that button is successfully displayed in the center of the div.

Conclusion

To center the button, you can use the “display”, “align-item”, and “justify-content” properties of CSS. These properties allow you to set the button in the center of the div or any element when you specify the value of the display property as “flex”, align-item, and justify-content as “center”. In this article, we have explained how to center the button using Flexbox with the help of an appropriate example.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.