Add image to left of text via css

Css

Css Problem Overview


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!

Css Solutions


Solution 1 - Css

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

Solution 2 - Css

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.

Solution 3 - Css

Try something like:

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

}

Solution 4 - Css

This works great

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

Solution 5 - Css

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris ConwayView Question on Stackoverflow
Solution 1 - CssJon SmockView Answer on Stackoverflow
Solution 2 - Csstomasz86View Answer on Stackoverflow
Solution 3 - CssTraingamerView Answer on Stackoverflow
Solution 4 - CssШууданч ЗөгийView Answer on Stackoverflow
Solution 5 - CssTokiView Answer on Stackoverflow