开发者

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; tex开发者_如何学Got-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


Testing this in Chrome, you need to add

padding: 0px;

To the CSS.


padding: 0px solves the horizontal centering

whereas,

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


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.


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


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;

}


What about:

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


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.


make sure:

box-sizing : content-box;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜