Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I horizontally center a button element in a div element?

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?

like image 828
weilou Avatar asked Mar 08 '13 17:03

weilou


People also ask

How do I center all elements in a div horizontally?

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.

How do you center an element in a div?

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.

How do I center something 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 .


2 Answers

button {     margin:0 auto;     display:block; } 

button {    margin: 0 auto;    display: block;  }
<div>    <button>Button</button>  </div>
like image 125
j08691 Avatar answered Sep 18 '22 17:09

j08691


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 } 
like image 29
Phillip Schmidt Avatar answered Sep 17 '22 17:09

Phillip Schmidt