John Ohara John Ohara - 5 months ago 11
CSS Question

Css selector giving strange results

I'm getting some strange results from one of my selectors.

After a reset, I have some base settings - this being one:

a:not([class]) {
text-decoration:underline;

&:link, &:visited, &:hover, &:active {
color:@primaryColor;
}
&:hover {
text-decoration:none;
}
}


It does the job - partly.

This anchor with no href works

<a class="link-more mt24">Learn more</a>


However this anchor with an href doesn't work.

<a class="link-more mt24" href="https://www.bbc.co.uk">Learn more</a>


By work I mean that the first link correctly gets ignored, the second link isn't ignored even though it has a class.

For completeness, this is what Less is pushing out:

a:not([class]) {
text-decoration: underline;
}
a:not([class]):link,
a:not([class]):visited,
a:not([class]):hover,
a:not([class]):active {
color: #03a9f4;
}
a:not([class]):hover {
text-decoration: none;
}


Any ideas?

Answer

The behavior is as expected. a:not([class]) would select and style a elements that don't have the class attribute. So the third a in the below snippet is underlined as it doesn't have class attribute.

The first a doesn't get the underline because a elements without href attribute assigned to it won't get the underline by default. This is because the text-decoration: underline is normally set using a selector like a:-webkit-any-link (WebKit specific, but other UA's will have similar ones).

The second a has the underline because of the default styling (indicated above) that is applied by the UA for a tags. The a:not([class]) does not have any effect on it (that is, it is not the reason for the underline) because the selector won't even point to that element.

If you want all the a elements with class to not have underline then use a[class] and remove the underline.

a[class] { /* if you remove this selector, the second link will be underlined */
  text-decoration: none;
}
a:not([class]) {
  text-decoration: underline;
}
a:not([class]):link,
a:not([class]):visited,
a:not([class]):hover,
a:not([class]):active {
  color: #ff0000;
}
a:not([class]):hover {
  text-decoration: none;
}
<a class="link-more mt24">Learn more</a>
<a class="link-more mt24" href="https://www.bbc.co.uk">Learn more</a>
<a href="https://www.bbc.co.uk">Learn more</a>

Comments