How to style readonly attribute with CSS?

后端 未结 9 1676
忘了有多久
忘了有多久 2020-12-12 21:45

I\'m currently using readonly=\"readonly\" to disable fields. I\'m now trying to style the attribute using CSS. I\'ve tried using

input[readonly] {
/*styling         


        
9条回答
  •  情深已故
    2020-12-12 21:58

    Loads of answers here, but haven't seen the one I use:

    input[type="text"]:read-only { color: blue; }
    

    Note the dash in the pseudo selector. If the input is readonly="false" it'll catch that too since this selector catches the presence of readonly regardless of the value. Technically false is invalid according to specs, but the internet is not a perfect world. If you need to cover that case, you can do this:

    input[type="text"]:read-only:not([read-only="false"]) { color: blue; }
    

    textarea works the same way:

    textarea:read-only:not([read-only="false"]) { color: blue; }
    

    Keep in mind that html now supports not only type="text", but a slew of other textual types such a number, tel, email, date, time, url, etc. Each would need to be added to the selector.

提交回复
热议问题