Home Ask Login Register

Developers Planet

Your answer is one click away!

TheNorthFace February 2016

Forms: input + label as a placeholder

I'm working on adaptive placeholders for a form. Inspired by this http://blog.circleci.com/adaptive-placeholders I use <label> and give it style to make it look like a normal placeholder.

Like this:

input[type="text"][required] + label[placeholder]:before {
                content: attr(placeholder);
                display: inline-block;
                margin: 0 10px;
                padding: 0;
                color: #999999;
                white-space: nowrap;

Normally I target the placeholder for styling (eg. giving it a validation error class) like this:

.error::-webkit-input-placeholder {
                color: #000;

My first thought would be the following to set the .error class, but it doesn't work:

.error::-webkit-input[type="text"][required] + label[placeholder]:before {
                color: #000;

Any suggestions on how I properly can apply a CSS class for the method used above?

JSFiddle: https://jsfiddle.net/34ye51t5/



JamieC February 2016

It looks like you're running into specificity issues. Adding the following CSS works, but I would consider re-factoring your code to help avoid these problems.

input[type="text"].error + label[data-placeholder]:before{
  color: white;

First of all placeholder is not a valid attrinbute for a label - it's for inputs only. You could change this to a data attribute, but I don't really see the point in this, you might as well just use the label as follows (alt is also not a valid attribute

<label for="last_name">Last name</label>

You'll then need to adjust the positioning etc. of this label.

I would also consider adding a class to a wrapper for the label/input combination for better control and to avoid said specificity issues. I've done a quick example using BEM naming conventions using sass as a preprocessor. This isn't meant to replicate the behavior of your code, but should act as a good starting point.


You can then add the error class as a 'modifier' to each element to allow you to style these independently e.g. .fancy__input--error and not rely on using things like the + selector.

Post Status

Asked in February 2016
Viewed 1,211 times
Voted 5
Answered 1 times


Leave an answer

Quote of the day: live life