通过 css 将图像添加到文本的左侧

我怎样才能添加一个图像到一些文本通过 css?

我知道了:

<span class="create">Create something</span>

我想用 css 在左边添加一个16x16的图像。这可能吗? 或者我应该像这样手动添加这个图片:

<span class="create"><img src="somewhere"/>Create something</span>

我宁愿不必手动更改所有的地方,这就是为什么我想通过 CSS 做到这一点。

谢谢!

181957 次浏览
.create
{
background-image: url('somewhere.jpg');
background-repeat: no-repeat;
padding-left: 30px;  /* width of the image plus a little extra padding */
display: block;  /* may not need this, but I've found I do */
}

Play around with padding and possibly margin until you get your desired result. You can also play with the position of the background image (*nod to Tom Wright) with "background-position" or doing a completely definition of "background" (link to w3).

Try something like:

.create
{
margin: 0px;
padding-left: 20px;
background-image: url('yourpic.gif');
background-repeat: no-repeat;


}

Very simple method:

.create:before {
content: url(image.png);
}

Works in all modern browsers and IE8+.

Edit

Don't use this on large sites though. The :before pseudo-element is horrible in terms of performance.

This works great

.create:before{
content: "";
display: block;
background: url('somewhere.jpg') no-repeat;
width: 25px;
height: 25px;
float: left;
}

For adding background icon always before text when length of text is not known in advance.

.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}