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


83

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

我有这个:

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

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

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

我宁愿不必手动更改所有位置,这就是为什么我想通过CSS进行更改。

谢谢!

Answers:


126
.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 */
}

尝试填充和可能的边距,直到获得所需的结果。您也可以使用“ background-position”来处理背景图像的位置(*向Tom Wright致意),或者完全定义“ background”(链接到w3)。


可能要指定图像的位置。但是,否则,请致电。
汤姆·赖特

1
如果您确保行高足够大以适合垂直放置图像,则可以避免将display属性设置为block,否则,[可能]您会看到它被切掉并希望将其制成block元素。
Zack The Human

您可以使用优化选项代替前两行:background:url('somewhere.jpg')no-repeat;
Alexis Gamarra 2014年

1
当页面显示在屏幕上时,此方法有效,但是大多数浏览器在打印时默认情况下会忽略背景图像,这样您将在该图像应留有空白的地方。为此必须有一种解决方法!
维维安河

36

很简单的方法:

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

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

编辑

不过,请勿在大型网站上使用此功能。:before伪元素的性能令人恐惧。


12

尝试类似:

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

}

但不要忘记不重复
Traingamer

1
width:2em; background-size: contain;为了限制图像的大小,添加可能也很有用。
达米安·格林

8

这很棒

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

1
您可以详细说明这一点,以及为什么会起作用。为什么他的代码没有其他?
Yaje 2014年

1
里面应该有东西url()吗?
达伦·库克

@Darren Cook-不知道您是否在讽刺,无​​论如何,您都必须在其中放置图片的网址。
乔瓦尼

3
@乔凡尼不要讽刺!我只是对答案进行了编辑,以使其更加清楚地表明它不是故意留空的。
达伦·库克

2

当事先不知道文本长度时,总是在文本之前添加背景图标。

.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.