oligofren
oligofren

Reputation: 22993

Unable to target xlink:href using attribute selectors

I am trying to avoid having to <use class="myicon" xlink:href="myicon" /> by simply targeting the value of the xlink:href attribute when styling my SVGs. None of the following selectors seem to work:

[xlink|href*=myicon], // I also set the namespace at the top of the file
[xlink:href*=myicon], 
[xlink\:href*=myicon] {
    color: yellow !important;
}

A few other questions on the site seem to imply that styling using the attribute selectors on namespaced attributes should be possible, even though plain html has no support for namespaced attributes, as it should just regard them as one word. But I cannot get it to work, so I am losing faith in just that.

Upvotes: 2

Views: 2082

Answers (2)

BoltClock
BoltClock

Reputation: 724452

As Blake Mann says, if you're listing all your selectors together like that, it won't work because [xlink:href*=myicon] is invalid, which causes your entire ruleset to be dropped. If you're trying different selectors, you need to try them one at a time.

[xlink|href*=myicon] works just fine, but make sure you've specified the XLink namespace and not the SVG namespace:

@namespace xlink 'http://www.w3.org/1999/xlink';

html {
    background-color: black;
}

[xlink|href*=myicon] {
    fill: yellow;
}
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <text id="myicon" y="16">Icon</text>
  </defs>
  <use xlink:href="#myicon" />
</svg>

Upvotes: 4

Blake Mann
Blake Mann

Reputation: 5490

You were definitely on the right track with what you were doing.. in fact, you have the right answer:

[xlink\:href*=myicon] {
    color: yellow !important;
}

The reason it isn't working is because the first two selectors you tried were invalid (both the | and : characters need to be escaped), and if a CSS selector contains invalid characters, the whole selector group gets thrown out.

Check this example as proof... the div (just using a div for simplicity, even though that's not quite right) should get set to be red, as that rule comes after the blue one, but because the selector group gets thrown out, that rule won't get applied. The other selector that does not have the invalid characters will apply though!

[xlink\:href*=myicon] {
    color: blue;
}

[xlink|href*=myicon],
[xlink:href*=myicon], 
[xlink\:href*=myicon] {
    color: red;
}
<div xlink:href="myicon">Lorem Ipsum</div>

Upvotes: 3

Related Questions