Html 对齐按钮元素中间的图像和文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9420642/
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
Align image and text in the middle of button element
提问by Stan
What would be the best and easiest way to align text and image vertically in the middle of button. Example:
在按钮中间垂直对齐文本和图像的最佳和最简单的方法是什么。例子:
button {
padding: 1px 6px 1px 6px;
}
button img {
width: 22px;
height: 22px;
}
<button>
<img src="http://latvijas-universitates-matematikas-un-informatikas-instituts.atver.lv/images/msn-icon.gif" alt="Text" />
<span>Text</span>
</button>
采纳答案by TimCodes.NET
button{
padding: 5px 6px 5px 30px;
background: url('http://latvijas-universitates-matematikas-un-informatikas-instituts.atver.lv/images/msn-icon.gif') no-repeat 5px center;
}
回答by 0b10011
While @paislee's solution works, it is not ideal. With the universal selector (*
) being used, everyelement is checked against it (as CSS is matched right-to-left). A better solution, especially if all children elements are known, is to match the elements individually. Ergo, button > img, button > span
is better than button > *
.
虽然@paislee 的解决方案有效,但并不理想。使用通用选择器 ( *
) 后,每个元素都会根据它进行检查(因为 CSS 从右到左匹配)。更好的解决方案,尤其是在所有子元素都已知的情况下,是单独匹配元素。因此,button > img, button > span
比button > *
.
button {
padding: 1px 6px 1px 6px;
}
/* Add this to align vertically */
button > img,
button > span {
vertical-align: middle;
}
<button>
<img src="https://placehold.it/50x50" alt="Text" />
<span>Text</span>
</button>
回答by Valamas
Padding + img height = line height. Could play with the padding a little. Would be easier if img was odd number height as center is one pixel and eitherside is even number of pixels.
填充 + img 高度 = 行高。可以玩一下填充。如果 img 是奇数高度,因为中心是一个像素,两边是偶数像素,那会更容易。
button{
padding: 1px 6px 1px 6px;
line-height: 24px;
}
button img{
width: 22px;
height: 22px;
vertical-align: middle;
}?
回答by Andrew Bacon
Since we're positioning fixed-height content, we can use absolute positioning.
因为我们定位的是固定高度的内容,所以我们可以使用绝对定位。
button{
padding: 7px 7px 7px 30px;
postion:relative;
}
button img{
width: 22px;
height: 22px;
position:absolute;
left:5px;
top:50%;
margin-top:-11px;
}?
Adjust padding and left positioning to desired look.
调整填充和左定位到所需的外观。