【发布时间】:2019-05-31 05:10:14
【问题描述】:
我的页面上有按钮,有时带有图标图像和文本标签,有时只有图标,没有文字。
我已经对按钮中的图像进行了样式设置,以便在右侧有一个边距,以便将图标与文本分开。
问题是因为那个边距,如果按钮中没有文字,图标不在按钮的中心,所以看起来很糟糕。
button {
border: none;
border-radius: 0.5rem;
background-color: pink;
line-height: 32px;
font-size: 1rem;
padding: 0.5rem;
}
button > img {
float: left;
margin-right: 0.5rem;
}
<div>
<p>
This looks OK:
</p>
<button>
<img src="https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/star-32.png"> OK
</button>
</div>
<div>
<p>
This doesn't (icon not in the center of the button):
</p>
<button>
<img src="https://cdn2.iconfinder.com/data/icons/ios-7-icons/50/star-32.png">
</button>
</div>
(见fiddle)
一个简单而明显的解决方法是将文本放在 span 元素中,然后使用 :only-child 设置图像元素的样式。
但是我将不得不更改我们代码库中已经使用这种样式的很多地方,并且我必须以某种方式说服我的开发人员始终将他们的按钮标签放在 span 元素中,只是为了使按钮 没有文本标签看起来不错。
是否有另一种方法可以让我的 HTML 代码保持不变,同时消除图像上的边距(如果后面没有文本)?
【问题讨论】:
-
可以使用 js/jquery 但纯 css 如果有人有解决方案我会很感兴趣。 +1