Reputation: 16519
How can I add an image to some text via 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:
<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.
thanks!
Upvotes: 91
Views: 196099
Reputation: 294
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;
}
Upvotes: 8
Reputation: 111
This works great
.create:before{
content: "";
display: block;
background: url('somewhere.jpg') no-repeat;
width: 25px;
height: 25px;
float: left;
}
Upvotes: 9
Reputation: 919
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.
Upvotes: 44
Reputation: 9641
.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).
Upvotes: 134
Reputation: 1423
Try something like:
.create
{
margin: 0px;
padding-left: 20px;
background-image: url('yourpic.gif');
background-repeat: no-repeat;
}
Upvotes: 12