Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<input> with display:block inside a text-align:center div

Tags:

html

css

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"...)

like image 636
Yuval A. Avatar asked Jan 15 '11 08:01

Yuval A.


People also ask

How do I center a div with a display block?

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.

How do I center an input box inside a div?

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.

How do I center text in a div inline block?

Inline block divs can be centered by applying text-align:center to their parent.

How do you center a text box in input?

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.


2 Answers

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 ;)

like image 130
stecb Avatar answered Sep 20 '22 14:09

stecb


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" />
like image 37
davin Avatar answered Sep 21 '22 14:09

davin