72

I understand that css rules can target elements specified by attribute values, e.g.:

input[type="text"] {}

Can I make a rule that targets elements which omit a certain attribute? For example, can I target elements that lack an href or elements that don't specify a type?

4 Answers 4

115

You can follow this pattern:

a:not([href])
input:not([type])

The attribute selector is used to select elements with the specified attribute.

:not is supported in all modern browsers and IE9+, if you need IE8 or lower support you're out of luck.

4
  • +1 Here's a demo for the curious: jsfiddle.net/Z2sHD/2 Side note: Correct me if I'm wrong, but <a> requires an href attribute to be present in order to be, yknow, valid HTML.
    – Mog
    Commented Aug 23, 2011 at 19:15
  • 6
    @Wesley it doesn't, an a element can be simply an anchor, with only the name attribute
    – Einacio
    Commented Aug 23, 2011 at 19:19
  • Ah yes that's right, not sure where I got that idea. I think I was thinking of something else entirely.
    – Mog
    Commented Aug 23, 2011 at 19:20
  • Also worth noting that it's possible to select ONLY all elements that contain NO (custom) attributes. I was racking my brain for a bit before arriving at the admittedly obvious answer. While you can't do something like foo:not(foo[*]){ color: red; }, you can do a standard CSS cascade like foo{ color: red; } foo[green]{ color: green; } foo[blue]{ color: blue; } to define a "default" value. This has the nice side effect of making any other/unrecognized value fallback to the default, instead of defining things like foo[normal],foo[default]{ color:red; }.
    – Beejor
    Commented May 25, 2019 at 17:56
2

The only solution that worked for me was to place a:link { } within my code.

I also tried

a:not([href]) input:not([href=""]) input:not([href~=""])

But for a .scss file with multiple a tags used as standard code blocks (not my idea), this was the only solution.

1

For links you can simply use:

a { color: red; }
a:link { color: green; }

fiddle: http://jsfiddle.net/ZHTXS/ no need for javascript.

For form attributes, use the not attribute pattern noted above input:not([type]) and if you need to support older versions of IE, I'd probably add a class and use an IE specific style sheet linked with conditional comments.

1
  • 2
    While this is a clever answer for anchors, it applies only to anchors.
    – animuson
    Commented Aug 23, 2011 at 19:20
1

You can always set different style to a and a href

Check this: http://jsfiddle.net/uy2sj/

1
  • As my comment stated in the below answer, this would only be useful for anchors. While the title may state anchors, the OP specifies all elements and even includes an input example.
    – animuson
    Commented Aug 23, 2011 at 19:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.