How to Center a Button Both Horizontally and Vertically within a Div
In our snippet you can find some solutions to the problem of centering a button within a <div>. One of our solutions to the problem also includes using Flexbox.
If you need to center a button within a <div>, this snippet provides a few solutions.
We’ll show you step by step how to achieve this.
Let’s start with the HTML structure.
Create HTML
- Use a
<div>with an id “wrapper”. - Add a
<button>with a type “button”.
How to Center a Button within a Div
<div id="wrapper">
<button type="button">W3Docs</button>
</div>Add CSS
- Set the width, height, and border properties for the wrapper.
- Specify the height, width, top, and left properties for the button.
- Set the position to “relative” so the button can be positioned relative to its normal flow.
- Apply negative margin values to shift the button back to the center.
How to Center a Button within a Div
#wrapper {
width: 100%;
height: 400px;
border: 2px solid #000;
}
button {
height: 20px;
position: relative;
margin: -10px -50px;
width: 100px;
top: 50%;
left: 50%;
}The top: 50% and left: 50% properties move the button’s top-left corner to the center of the wrapper. The negative margins (-10px for height, -50px for width) shift it back by exactly half its dimensions to achieve perfect centering. Note: A more robust modern alternative is using transform: translate(-50%, -50%) instead of fixed negative margins.
Let’s see the result of our code.
Example of centering a button inside a <div>:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
#wrapper {
width: 100%;
height: 400px;
border: 2px solid #000;
}
button {
height: 20px;
position: relative;
margin: -10px -50px;
width: 100px;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<div id="wrapper">
<button type="button">W3Docs</button>
</div>
</body>
</html>Result
<div class="demo px-2.5 mt-1 mb-5">``<div id="wrapper"> <button type="button">W3Docs</button> </div> </div>
Next, let’s see an example where we use Flexbox to achieve the effect we want.
Example of centering a button inside a <div> using Flexbox:
How to Center a Button within a Div
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
#wrapper {
width: 100%;
height: 300px;
border: 2px solid #000;
display: flex;
align-items: center;
justify-content: center;
}
button {
height: 30px;
width: 90px;
}
</style>
</head>
<body>
<div id="wrapper">
<button type="button">W3Docs</button>
</div>
</body>
</html>In the example above, we set the display to “flex”, then specified the values of align-items and justify-content as “center”.