gbhall
gbhall

Reputation: 13279

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

Upvotes: 59

Views: 216881

Answers (9)

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

padding: 0px solves the horizontal centering

whereas,

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

line-height: 0px;

Upvotes: 22

Rigers Leka
Rigers Leka

Reputation: 483

I notice the same issue due to some UI fixies. Below, I'll demonstrate how I fixed this bug:

.html

<button className='registration_button'>
 Registration
</button>

.scss

  .registration_button {

    //solve the vertical centering
    margin: auto;
    line-height: 1.25rem; 

    //solve the horizontal centering    
    padding: 0px;

}

Upvotes: 0

vinay chowdary
vinay chowdary

Reputation: 29

make sure:

box-sizing : content-box;

Upvotes: 0

Abhishek
Abhishek

Reputation: 682

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.

Upvotes: -2

RadDog25
RadDog25

Reputation: 29

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

Upvotes: 2

TheQ
TheQ

Reputation: 516

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.

Upvotes: 0

Zwik
Zwik

Reputation: 654

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.

Upvotes: 4

Tejs
Tejs

Reputation: 41236

Testing this in Chrome, you need to add

padding: 0px;

To the CSS.

Upvotes: 119

Gabe
Gabe

Reputation: 50493

What about:

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

Upvotes: -1

Related Questions