This write-up will demonstrate how to center the button element within a div using CSS.
How to Center a Button Within a div using CSS?
In CSS, we will utilize the following properties to center the button inside a div:
So, let’s elaborate on each one by one!
Method 1: Center a Button Within div Using CSS display Property
To control how a selected HTML element will behave, the “display” property is used. This property is helpful in making elements flexible to set them at a specific place, such as setting the element in the center, displaying property with justify-content, and align-items can be used.
Let’s take an example to acknowledge the working of display property to center the button within the div element.
Example
Here, we have a button inside the container on our web page. So, let’s position it in the center:
In our HTML file, we have specified a button using the “<button>” tag and declared it inside the “<div>“. Now specify the div within <body> tags.
HTML
In the CSS file, we will utilize the “border” property with the value “solid 1.5px”, where solid is the type, and 1.5px is the width of the border. Now, assign an appropriate height to div using the “height” property like “7rem”. The “display” property will be used with the value “flex” to make the defined portion flexible.
In the next step, we will align the button to center horizontally and vertically using the value “center” for the “justify-content” and “align-items” properties.
CSS
border: solid 1.5px;
height: 7rem;
display: flex;
justify-content: center;
align-items: center;
}
Save the code and run the HTML file in your browser:
As you can see, we have successfully centered a button inside a div using CSS properties.
Method 2: Center a Button Within div Using CSS position Property
The “position” property is utilized to place HTML elements at a specific position. The combination of this property with other CSS properties helps in achieving the desired results gracefully.
Example
In the div element, we will take the value of the “text-align” property as “center” to place the button horizontally in the center. For the button element, specify the “position” property with the value “relative”; this will make the button element to position relative from its standard position. Next, we will set the “top” property value to “40%” to align the button in the center vertically.
CSS
border: solid 1.5px;
height: 7rem;
text-align: center;
}
button {
position: relative;
top: 40%;
}
Output
We have explained the easiest methods to center a button Inside a div using CSS.
Conclusion
To center a button inside a div, the “display” or “position” property will be utilized. The display property will be used with the combination of other properties, such as align-items and justify-content, to center the button element. Moreover, the position property is used with text-align and top property to get the desired result. In this write-up, we have explained how to center a button element within a div using CSS.