0

Is it possible to use CSS to make an element the same color as the default <a> color?

If so, how?

user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

2

I think there is no keyword to specify a color as the same color of a link (although we does have keywords to specify system colors). There is only a workaround is using a script to build some CSS rule styling the color the same as of a link and use this style for your element.

//Get the default link color in the current browser
var a = $("<a href='#'>").appendTo('body');
var linkColor = a.css('color');
a.remove();
//build the CSS rule 
var ss = document.styleSheets[0];
if('addRule' in ss) {
  ss.addRule(".defaultLinkColor", "color: " + linkColor);
} else if('insertRule' in ss){
  ss.insertRule(".defaultLinkColor { color: " + linkColor + ";}", 0);  
}

Then you can apply the class defaultLinkColor for your element:

<span class='defaultLinkColor'>I'm not a link</span>

Demo.

King King
  • 61,710
  • 16
  • 105
  • 130
  • 1
    Interesting approach. Works in Chrome, but not FF29 – user1032531 May 04 '14 at 14:17
  • @user1032531 it's because `FF` does not (maybe **never**) support `addRule` method, it supports only the `insertRule` method. I updated the code as well as the demo. – King King May 04 '14 at 14:31
  • That's because `addRule()` is non-standard. Presumably Chrome supports it in addition to `insertRule()` for interop reasons. – BoltClock May 04 '14 at 14:33
  • A simpler cross-browser way (when you are using jQuery anyway) is to set the property directly on the elements: `$('.defaultLinkColor').css('color', linkColor);`. – Jukka K. Korpela May 04 '14 at 14:36
  • @JukkaK.Korpela yes, but it works in a different way, any newly created element should have style changed with that line of code. – King King May 04 '14 at 14:38
  • I like the add/insert rule approach more since it better allows for added elements. Before seeing your edited post, I was playing with the same thing, but kept getting `SecurityError: The operation is insecure. ss.insertRule(".defaultLinkColor { color: " + linkColor + ";}", 0);` error. I think your version well (note that your demo link is broken). Thank you – user1032531 May 04 '14 at 14:46
  • @Jukka K. Korpela: FYI, I just reopened [this related question](http://stackoverflow.com/questions/4774022/whats-default-html-css-link-color) and updated my answer with some new findings based on your comment. I can't think of a good way to edit the question into something that's at least worth all the upvotes it has received over time, but it is on-topic nonetheless. – BoltClock May 04 '14 at 15:00