[css] Simple CSS: Text won't center in a button

In Firefox 'A' shows in the middle, on Chrome/IE it doesn't:

<button type="button" style="width:24px; text-align:center; vertical-align:middle">A</button>

Note the following has the same results:

<button type="button" style="width:24px;">A</button>

Edit: Now seems to be fixed in Chrome 5.0

This question is related to css

The answer is


What about:

<input type="button" style="width:24px;" value="A"/>

As a more brute force method that I found worked for me:

First wrap the text inside the button in a span, and then apply this css to that span

var spanStyle = {
      position: "absolute",
      top: "50%",
      left: "50%",
      transform: "translate(-50%, -50%)"
    }

*above setup for inline styling


padding: 0px solves the horizontal centering

whereas,

setting line-height equal to or less than the height of the button solves the vertical alignment.


You can bootstrap. Now a days, almost all websites are developed using bootstrap. You can simply add bootstrap link in head of html file. Now simply add class="btn btn-primary" and your button will look like a normal button. Even you can use btn class on a tag as well, it will look like button on UI.


make sure:

box-sizing : content-box;

The problem is that buttons render differently across browsers. In Firefox, 24px is sufficient to cover the default padding and space allowed for your "A" character and center it. In IE and Chrome, it does not, so it defaults to the minimum value needed to cover the left padding and the text without cutting it off, but without adding any additional width to the button.

You can either increase the width, or as suggested above, alter the padding. If you take away the explicit width, it should work too.


Usualy, your code should work...

But here is a way to center text in css:

.text
{
    margin-left: auto;
    margin-right: auto;
}

This has proved to be bulletproof to me whenever I want to center text with css.