Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Button - Vertically centre text

I have a Button that is a simple anchor tag styled with the following -

.buyBtn{ 
   background:url(../images/buyBtn.png) no-repeat; 
   padding-top:4px; 
   width:97px;     
   height:28px; 
   margin-top:14px;
}
.buyBtn a{
   color:#fff!important; 
   font-weight:normal!important; 
   text-decoration:none;
   padding-left:27px;  
   padding-top:12px; 
   text-shadow:none!important;
}

I'm having problems vertically centering the text within the button, it appears fine in some devices, but off centre in others.

Can anybody recommend a way to fix this or a better solution to achieve the same result?

Cheers

like image 534
Dancer Avatar asked Nov 24 '11 14:11

Dancer


People also ask

How do I center text vertically in a button CSS?

Use line-height to center it vertically. I usually use the same value as its height. Works only when you know the height. I set height to 0 and line-height to zero and this worked!

How do you center text vertically in a text box?

1 Select the text you want to center between the top and bottom margins. 2 On the Page Layout tab, click the Page Setup Dialog Box Launcher. 3 Select the Layout tab. 4 In the Vertical alignment box, click Center 5 In the Apply to box, click Selected text, and then click OK.


4 Answers

Use line-height to center it vertically. I usually use the same value as its height.

like image 152
bchhun Avatar answered Sep 17 '22 17:09

bchhun


HTML:

<div class="buyBtn"><a href="#">Button</a></div>

CSS:

.buyBtn{ 
    background:url(../images/buyBtn.png) no-repeat; 
    width:97px;     
    height:28px; 
    display: table-cell;
    vertical-align: middle;
}

.buyBtn a{
    color:#fff!important; 
    font-weight:normal!important; 
    text-decoration:none;
    padding-left:27px;
    text-shadow:none!important;
}

No need to use padding-top or margin-top for vertical align. Just use display: table-cell; and vertical-align: middle;. Thats it.

like image 26
Ariful Islam Avatar answered Sep 17 '22 17:09

Ariful Islam


Flexbox helped me nail it. Assume you have an excel button (an anchor tag, really).

HTML

<a class="btn-excel" href="/Export/ExportListToExcel">
    Export To Excel
</a>

CSS

.btn-excel {
    background-color: #32CD32; /*lime green*/
    color: #fff;
    outline: none;
    border-radius: 0.3rem;
    text-decoration: none;
    width: 5rem;
    height: 2.5rem;
    /* Flex rules 'em all */
    display: flex;
    justify-content: center;
    align-items: center;
}
.btn-excel:hover {
    background-color: #808000; /*olive*/
    cursor: pointer;
    text-decoration: none;
}
like image 27
Amjad Abujamous Avatar answered Sep 19 '22 17:09

Amjad Abujamous


I would use line-height as bchhun as mentioned. Also, padding-top & padding-bottom can help.

like image 31
peduarte Avatar answered Sep 21 '22 17:09

peduarte