10

Why can't I select elements by their href-attribute?

CSS

/* Works */
svg image[type=overlay]{
    outline: 3px solid blue;
}

/* Doesn't work */
svg image[href*='temp']{
    outline: 5px solid red;
}

/* Doesn't work either */
svg image[href='wcs/WFL/position/temp2.png']{
    outline: 5px solid red;
}

SVG

<image display="inline" type="overlay" width="148" height="90" x="920" y="918" transform="" href="wcs/WFL/position/temp2.png"><title>B02003
Temp: 2</title></image>

I did notice the browsers turns the href attribute to xlink:href but image[xlink:href*='temp'] doesn't work either.

How can I make this work?

Edit: The SVG uses the following namespaces, I think this causes the problem but I don't know how to get around it.

xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:svg="http://www.w3.org/2000/svg"

Fiddle

Jonathan
  • 8,771
  • 4
  • 41
  • 78

1 Answers1

10

Demo Fiddle

Firstly, in order to use xlink slectors, you need to to declare the xlink namespace at the top of your stylesheet according to the spec:

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

Then, you can use the following attribute selector with a namespace prefix:

svg image[xlink|href*="temp"] {
    outline: 3px solid red;
}

The attribute name in an attribute selector is given as a CSS qualified name: a namespace prefix that has been previously declared may be prepended to the attribute name separated by the namespace separator "vertical bar" (|). In keeping with the Namespaces in the XML recommendation

SW4
  • 69,876
  • 20
  • 132
  • 137
  • 5
    Alternatively, you can use the wildcard namespace on the attribute `[*|href]` (unless you have images with two different types of href attributes!). More at [this answer about `.querySelector()`, for which declaring namespaces isn't an option](http://stackoverflow.com/a/23047888/3128209). – AmeliaBR Dec 13 '14 at 04:46
  • Pleae note that this namespace declaration have to be placed at the top of your css file. More precisely, as stated in this thread https://stackoverflow.com/questions/24628932/do-css-namespace-attribute-selectors-work-with-xhtml-html-elements, *a normal CSS rule must not precede any \@namespace rules, or the \@namespace rules are invalid*. The CSS Namespaces Module Level 3 http://www.w3.org/TR/css3-namespace/ says that > Any \@namespace rules must follow all \@charset and \@import rules and precede all other non-ignored at-rules and style rules in a style sheet. – AlexLaforge Oct 15 '19 at 12:13