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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/735394/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:30:13  来源:igfitidea点击:

Add image to left of text via css

css

提问by Chris Conway

How can I add an image to some text via css?

如何通过css将图像添加到某些文本中?

I've got this:

我有这个:

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

and I want to add a 16x16 image to the left of that by using css. Is this possible or should i just manually add this image like so:

我想使用 css 在左侧添加一个 16x16 的图像。这是可能的还是我应该像这样手动添加这个图像:

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

I'd rather not have to manually change all of the places which is why I wanted to do it via css.

我宁愿不必手动更改所有位置,这就是我想通过 css 进行更改的原因。

thanks!

谢谢!

回答by Jon Smock

.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).

使用填充和可能的边距进行调整,直到获得所需的结果。您还可以使用“背景位置”或完全定义“背景”(链接到 w3来处理背景图像的位置(*向 Tom Wright 点头)。

回答by tomasz86

Very simple method:

非常简单的方法:

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

Works in all modern browsers and IE8+.

适用于所有现代浏览器和 IE8+。

Edit

编辑

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

但是不要在大型​​网站上使用它。:before 伪元素在性能方面很糟糕。

回答by Traingamer

Try something like:

尝试类似:

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

}

回答by Шууданч З?гий

This works great

这很好用

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

回答by Toki

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;
}