12

I've read that HTML "boolean attributes" such as readonly, disabled, required (etc.) can either be blank or have a value of their name. And people seem to be using both styles (see How should boolean attributes be written?)...

So it seems that the best way to accommodate this is to write your CSS like:

input[readonly], input[readonly="readonly"] {
}

(https://stackoverflow.com/a/19644231/1766230)

But is there a more concise way to write this? Maybe using some CSS3 attribute selector magic? I've tried input[readonly*=""], but without luck.

Community
  • 1
  • 1
Luke
  • 18,811
  • 16
  • 99
  • 115

2 Answers2

11

As @JoshC writes in a comment, you can simply use input[readonly]. This CSS selector (which is ignorant of all markup serialization issues) matches an input element that has the readonly attribute, no matter what its value is. The XHTML (XML) requirement that every attribute specification must include a value does not affect this.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
7

Boolean values in HTML don't need an actual value. They are true if they exist and false if they don't.

However, In XHTML boolean values need to be set as a string that contains the name of the attribute set.

In HTML

<input ... readonly>

The CSS

input[readonly] { ... }

In XHTML which is annoying and I want to avoid at all costs

<input ... readonly="readonly" />

The CSS

input[readonly="readonly"] { ... }

Edit: As a lot of people point out, you can write just readonly in XHTML CSS since matching the existence of the attribute would work even if the attribute is set to something such as readonly="readonly".

The CSS for XHTML is the same

input[readonly] { ... }

Unless you are using the CSS in both XHTML and HTML documents there is no need to write both forms of the selector. Just stick to HTML with <input readonly> and input[readonly]

OdraEncoded
  • 3,064
  • 3
  • 20
  • 31
  • 1
    There is no need to use the longer form even with XHTML. – Jukka K. Korpela Oct 28 '13 at 21:13
  • I'm trying to think of a way to write the CSS so that it is portable and always valid (for modern browsers). It's valid HTML to have either just `readonly` or to have `readonly="readonly"`, so I don't want to assume one style over the other. – Luke Oct 28 '13 at 21:15
  • 1
    `[readonly]` is just an attribute selector. If the attribute is set, regardless of its value or whether or not the attribute is valid, it will match. Why do you have reason to believe it doesn't work? – cimmanon Oct 28 '13 at 21:21
  • 1
    Tested again and this does work. http://jsfiddle.net/luken/WBkLV/ Something must have been wrong with my initial test. – Luke Mar 03 '14 at 22:13