Search code examples
htmlcssimagestylesheet

Add image to link with CSS


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?


Solution

  • 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/