CSS :placeholder-shown

Publikováno: 4.2.2019

One of the first plugins that would hit a new framework in the early days of JavaScript frameworks was a placeholder plugin, which is why we were so excited when HTML5 brought us the placeholder attribute. Then CSS lovers like me were thrilled when the CSS spec allowed us to style placeholders. One recent problem […]

The post CSS :placeholder-shown appeared first on David Walsh Blog.

Celý článek

One of the first plugins that would hit a new framework in the early days of JavaScript frameworks was a placeholder plugin, which is why we were so excited when HTML5 brought us the placeholder attribute. Then CSS lovers like me were thrilled when the CSS spec allowed us to style placeholders.

One recent problem I faced was wanting to apply a specific font-family to an <input> element but only when that element contained text. My initial thought was needing to set the font-family on the <input> and then re-apply the body’s font-family on the ::placeholder but that didn’t seem ideal — it seemed like a maintenance cost.

I took to Twitter for a better solution and luckily Facundo Corradini provided it: :placeholder-shown. The :placeholder-shown pseudo-selector targets an <input> element’s placeholder only when it’s shown, and thus I could select just the placeholder but not the input’s text:

/* Applying style to input applies to both input text and placeholder */
input { color: red; }

/* Applying style *just* to placeholder */
input::placeholder { color: blue; }

/* Applying style to input when placeholder is shown */
input:placeholder-shown { color: yellow; }

/* Applying style to input but *not* placeholder */
input:not(:placeholder-shown) { color: green; }

:placeholder-shown is an awesome pseudo-selector that can be used to more effectively style placeholders and their elements depending on state. Creativity isn’t just a design term — it’s a way of thinking for developers to solve interesting problems!

The post CSS :placeholder-shown appeared first on David Walsh Blog.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace