Add image to link with CSS

16,980

Solution 1

You could do this with jQuery too.

<a href="#" class="imageLink">Some Link</a>

$('.imageLink').each(function(){
   $(this).append(' <img src="YOUR IMAGE HERE">'); 
});

http://jsfiddle.net/jasongennaro/6Nc3n/

EDIT:

I realized that the OP also said the distance from the start position of the link text to the start position of the image is always the same

So I modified the code

var finalWidth = 0;
var getWidth;

$('.imageLink').each(function(){
    getWidth = $(this).width();      
    if(getWidth > finalWidth){
      finalWidth = getWidth;
    }
});

finalWidth +=15;

$('.imageLink').each(function(){
   var getText = $(this).text();
    $(this).html('<span style="display:inline-block; width:' + finalWidth + 'px;">' + getText + '</span>');
   $(this).append(' <img src="http://icdn.pro/images/en/l/e/left-arrow-icone-3702-32.png">');
   $(this).css('textDecoration','none'); 

});

What this does is get the width of each link text. If checks if that width is the longest, if not ignores, but if yes, then makes it the finalWidth. This finalWidth then added to a new span created around the text and styled with inlineblock.

Updated Fiddle

http://jsfiddle.net/jasongennaro/6Nc3n/2/

Solution 2

it is "right center" not "center right" see example: http://jsfiddle.net/bingjie2680/ZtLCA/

it also works when you want them to be same distance between text link and image see example: http://jsfiddle.net/bingjie2680/ZtLCA/1/

Solution 3

What you need to do is give them a fixed width and a display: block.
Your css would look like this:

a.linkArrow
{
  background: transparent url('../images/abc.png') no-repeat right center;
  display: block;
  width: 100px;
}

Solution 4

a.linkArrow
{ 
    background: transparent url('../images/abc.png') no-repeat center right;
    display:block;
    width: /* image width PLUS the distance you want from the text px */;
    height: /* image height px */;
}
Share:
16,980
Patric
Author by

Patric

Please have a look at http://qoo.li I am a software engineer working in Switzerland.

Updated on June 04, 2022

Comments

  • Patric
    Patric almost 2 years

    I have some URLs to which I want to add the same image. I've got the following code:

    a.linkArrow
    { 
        background: transparent url('../images/abc.png') no-repeat center right;
        padding-right: 60px;
    }
    

    And a link example:

    <a class="inkArrow" href="#abc">Abc?</a>
    

    The problem is, the image appears on the left of the text of the link. I want that the image appears always on the right side of the text AND that the distance from the start position of the link text to the start position of the image is always the same. So when I have multiple links in a row that the images of the links align. The image should be clickable and lead to the same url as the link (I'm not sure if it is possible to enclose it in the same tag for this approach.

    Any ideas?