Styling HTML forms 23 min read

In a previous post we looked at styling HTML forms. In this one let’s try to take it further and mess around with it.

What are we going to do?

The aim is to add placeholder text to text inputs. If the element is not in focus we want to show only the placeholder text and hide the label text. But if in focus we want to hide the placeholder text and show the label text.

If that explanation didn’t work, here is a working example –

See the Pen Styling HTML forms 2 by hrishikesh mk (@avastava) on CodePen.0

We can add this effect with a few lines of extra javascript. The javascript in the  previous post looked like this –

It is to be noted that the desired effect works only with text inputs or elements that have the placeholder property. Ex – input[type=”text”],[type=”password”],[type=”number”], textarea element.

We have to create a collection of elements containing input elements ( excluding the types submit, checkbox and radio ) and textarea elements.

So let’s create a function which would help us identify the required elements. The function takes an element as input and tells us whether it is a required element or not.

Upgrading previous code

We need to add place holders for the input elements. So inside the for loop we add the following code

We take the label text and set it as the placeholder after checking if the element is of the required type. The label text is also hidden by setting the opacity property to zero. We are using the opacity property instead of display: none so that we can animate it using css transitions.

We used the input_fade function in the loop to change color of label text on focus. We have to slightly modify this function so that on focus the label text of the element becomes visible. But on blur if the value of the input field is empty we have to hide the label text and show the placeholder text instead.



Our aim was to create a beautiful form, but for this one to look good we need to add some more lines of code.

Styling placeholder text

The placeholder text should look the same as our label text.

Source – CSS Tricks

Adding a fading effect

Add this line of code to label text element and your beautiful form is ready. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *