CSS 按钮 - 垂直居中文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8258602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CSS Button - Vertically centre text
提问by Dancer
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
干杯
回答by bchhun
Use line-height to center it vertically. I usually use the same value as its height.
使用 line-height 使其垂直居中。我通常使用与其高度相同的值。
回答by Ariful Islam
HTML:
HTML:
<div class="buyBtn"><a href="#">Button</a></div>
CSS:
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.
无需使用padding-top
或margin-top
垂直对齐。只需使用display: table-cell;
和vertical-align: middle;
。就是这样。
回答by peduarte
I would use line-height
as bchhun as mentioned. Also, padding-top
& padding-bottom
can help.
我会line-height
像提到的那样使用bchhun。此外,padding-top
&padding-bottom
可以提供帮助。
回答by Jérémy Dutheil
Did you try setting a font-size to your link ? Each browser probably has its own default size, so that may be an hint. Be careful too with padding and width/height, you need to decrease the block size if you add padding 'cause the padding is included in the width. For example, a simple block of 100px width without padding will have a size of 100px : ok. Add a padding-left: 10px;
and your block now has a width of 110px. ;)
您是否尝试为链接设置字体大小?每个浏览器可能都有自己的默认大小,所以这可能是一个提示。也要注意填充和宽度/高度,如果添加填充,则需要减小块大小,因为填充包含在宽度中。例如,一个没有填充的 100px 宽度的简单块的大小为 100px :好的。添加 apadding-left: 10px;
并且您的块现在具有 110px 的宽度。;)
回答by GCJAmarasinghe
You can copy this code and put it as a CSS and adjust the things as you need
您可以复制此代码并将其作为 CSS 并根据需要进行调整
.btn-alignment{
width: 88px;
height: 40px;
margin: 0 auto;
padding: 0;
display: inline-block;
line-height: 40px;
margin-top: 9px;
text-align: center;
}