I don't want to add CSS to my div element (e.g. <div style="text-align: center;">
).
I only want to add CSS code to the button element.
<div> <button>Button</button> </div>
How can I center the button horizontally in this case?
To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
Center the text horizontally between the side margins Select the text that you want to center. On the Home tab, in the Paragraph group, click Center .
button { margin:0 auto; display:block; }
button { margin: 0 auto; display: block; }
<div> <button>Button</button> </div>
Others have already mentioned the margin: 0 auto;
method, but if you wanted an explanation, the browser splits up the available space in whatever container your element is in.
Also important to point out is you'll probably need to give your element a width, too, for this to work correctly.
So, overall:
button { display:inline-block; //Typically a button wouldn't need its own line margin:0 auto; width: 200px; //or whatever }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With