Introduction

Imagine designer designs a form where mandatory fields are highlighted using asterix and this asterix is a part of the placeholder. The issue begins when the asterix is highlighted by different color than the placeholder has.

Here’s an example:

example

How to do that using CSS? Well, the clean solution offers Webkit only - you can use :before pseudo-selector on :placeholder selector there. The dark side of this solution is this won’t work in IE nor Firefox. Here’s the code in LESS:

  input[type=text] {
    &.required {
        &::-webkit-input-placeholder { color: blue; 
            &:before { content: '*'; color: red; vertical-align: top; font-size: small; } }
    }
}

As you can see, we are moving the asterix slightly up to fake supperscript. Instead of using vertical-align: top; we can use vertical-align: super; - but then the placeholder can be pushed down and it does not look good.

So, that’s it. But now we are facing another problem - the dark side. How to deal with it? First step is that we have to do a fallback for other browsers.

Simply put the asterix into the placeholder attribute!

  <input type="text" name="name" placeholder="*First name" />

Now we are facing another problem - Webkit browsers displaying 2 asterixes! Well, that’s easy to fix using Javascript. Here’s a code in CoffeeScript:

  if RegExp(' AppleWebKit/').test navigator.userAgent
    $('input.required').each ->
        if RegExp(/^\*/).test $(this).attr('placeholder')
            $(this).attr('placeholder', $(this).attr('placeholder').replace '*', '' )

Voila, that’s it! So, webkit browsers display highlighted asterix, although other browsers display at least some asterix…

Complete solution

Cool, huh?

Support

So far this works in Webkit browsers only :(

Original post on my blog.


8,787 11 5