Reputation: 13
It's pretty common to apply icons to links using attribute selectors, or else to add a class via script. For example:
// HTML
<a href="foo.doc">This is an ordinary text link</a>
// CSS
a[href$=".doc"] {
background: url('bar.jpg') 0 0 no-repeat;
padding-left: 2em;
}
(etc)
This looks fine on standalone links, by which I mean this type of thing:
<p>Some paragraphs of text</p>
<p><a href="foo.pdf">Get the full report in a massive pretty PDF</a></p>
<p>More paragraphs</p>
But can look horrible on inline links, by which I mean this kind of stuff:
<p>Lorem ipsum dolor sit amet, <a href="foo.pdf">consectetur adipiscing</a> elit ... </p>
I'd like to be able to selectively apply icons to the first case but not the second.
So is there a way to reliably distinguish between the two (using script I imagine)?
Have tried to STFW but apologies if it's just my terminology fail.
Upvotes: 1
Views: 536
Reputation: 773
Specifically to distinguish between the two, you could use jQuery to compare every anchor to every parent containing an anchor and if they match, apply one style and if not apply another:
html:
<p>
Lorem ipsum dolor sit amet <a href="">link inside a paragraph with other text</a> Lorem ipsum dolor sit amet.
</p>
<p>
<a href="">link alone in a paragraph</a>
</p>
css:
.standalone {
background-color: red;
}
.inline {
background-color: green;
}
jQuery:
$(document).ready(function(){
$('a').each(function(){
var parent = $(this).parent().html().trim();
var myTag = $(this).wrap('<p/>').parent().html().trim();//wrap in a temp container to get the <a> as well
$(this).unwrap();
if(parent === myTag) {
$(this).addClass('standalone');
} else {
$(this).addClass('inline');
}
})
});
https://jsfiddle.net/y40o11hu/2/
This will do it for every link, but the initial selector can be whatever you'd like, so it can be reduced down to $('a[href$=".doc"]') or whatever.
Upvotes: 1
Reputation: 582
You can add element with icon like this:
a::before{
background: url('bar.jpg') 0 0 no-repeat;
width:2em;
height:2em;
content:" ";
}
Upvotes: 0
Reputation: 25413
You can specify stand-alone anchors by using more specific selectors in your CSS:
/* stand-alone anchor tag */
a {
}
/* inline anchor tag */
p a {
}
Upvotes: 0