I am trying to center a button without a div. The button is as follows
<body>
<button>Some Text</button>
</body>
I have tried using a few different techniques such as:
text-align: center
and
margin:0 auto;
but these don't work.
I am trying to center a button without a div. The button is as follows
<body>
<button>Some Text</button>
</body>
I have tried using a few different techniques such as:
text-align: center
and
margin:0 auto;
but these don't work.
Its simple, just make it display as a block element:
<body>
<button>Some Text</button>
</body>
button {
display: block;
margin: 0 auto;
}
Try this (You dont need a extra div or set a width)
CSS
button{
position: relative;
display: inline-block;
left: 50%;
transform: translateX(-50%);
}
Use this. It works:
<body>
<button style="position: relative; left: 50%;" >Some Text</button>
</body>
I used inline CSS since its easier to show on here.
If you use a set width then margin: 0 auto;
will work.
button {
display: block;
margin: 0 auto;
}
The reason you do not need to set a width for a <button>
with margin: 0 auto;
when you also set it to display: block;
is that a <button>
is a replaced element. Basically they are elements that have a predetermined width and height without the use of CSS.
Checkout this SO answer provided by @Brewal for a few more details.