With this:
<div id="parentdiv" style="text-align:center;width:600px;margin:auto;">
<input type="button" value="push me" />
</div>
The button is aligned to the center of the browser window (as desired) in FF, Chrome, IE7 and IE8.
But, add "display:block" to the button:
<div id="parentdiv" style="text-align:center;width:600px;margin:auto;">
<input type="button" style="display:block;" value="push me" />
</div>
The button is aligned to the center in IE7 - and is not aligned to the center in FF, Chrome and IE8.
Why? And can a button (or any <input>) with display:block be center-aligned in some way? (other than using <center> - which works on all browsers mentioned, btw - but is "forbidden"...)
You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.
The easiest way to center an input field in CSS is to put the input element inside a div element and then apply text-align: center; on this parent div element.
Inline block divs can be centered by applying text-align:center to their parent.
In modern browsers that support CSS 3 you can do an easy centering using these three lines of code: position: absolute; left: 50%; transform: translateX(-50%); The magic trick is in the transform: translatex(-50%); part. Usual CSS positions your element at the top left corner of the box.
This way it can work:
<input type="button" style="width:100px;margin:0 auto;display:block;" value="push me" />
To force a block input (originally display:inline element) to be centered, you have to set a fixed width and then the margin to 0 auto ;)
from the css standard:
This property describes how inline contents of a block are horizontally aligned
so when your elements (no matter what they are, divs, spans, inputs, etc.) are inline, text-align has an affect on them, and when theyre display:block, by standard definition, text-align will not align them
you can fix this by setting margin:0 auto and fixing a width, like steweb suggested, or alternatively (depending on your specific requirements):
<input type="button" style="display:inline-block;" value="push me" />
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