Patric
Patric

Reputation: 2989

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?

Upvotes: 3

Views: 18977

Answers (4)

Jason Gennaro
Jason Gennaro

Reputation: 34855

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/

Upvotes: 2

bingjie2680
bingjie2680

Reputation: 7773

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/

Upvotes: 6

Vap0r
Vap0r

Reputation: 2616

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

Upvotes: 1

Jose Faeti
Jose Faeti

Reputation: 12302

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

Upvotes: 1

Related Questions