Creating text input box in a creative way

Creating text input box in a creative way

3 min. read

See application in the fiddle below

HTML markup

<div id="inp-cover">
	<div id="inp" contenteditable="true"></div>
	<div id="placeholder">Enter some text</div>
</div>

CSS rules

Styling the div#inp-cover element

#inp-cover
{
	position:relative;
	width: 400px;
	border: 16px solid #fff;
	border-bottom-width: 0px;
	border-radius: 3px;
	box-shadow: 0px 0px 10px #ccc;
	overflow: hidden;
}

Result will look like the below image

Text box

Styling div#inp element, this is where user can input the text. The contenteditable attribute gives us the functionality of editing the content of the div element so that we can input the text in it.

#inp
{
	position:relative;
	height: 21px;
	font-size: 18px;
	font-family: Helvetica;
	white-space: pre;
	padding-bottom: 13px;
	outline: none;
	overflow: hidden;
	border-bottom: 3px solid #fff;
	z-index:2;
}

Result of combining above css rules will look like the below image

Text box

Now, styling the placeholder( div#placeholder ) for the text input, we will be creating a false placeholder for the text input box.

#placeholder
{
	position:absolute;
	top:0px;
	left:0px;
	bottom:3px;
	color:#ccc;
	font-size:18px;
	font-family: Helvetica;
	z-index:1;
}

Final result will look like the below image after applying all the above css rules

Text box

In above css rules we can see that the input box (div#inp) is placed above the placeholder (div#placeholder) using the z-index css property. Input box is assigned greater value of z-index than the placeholder that's why it is one layer up than placeholder.

Hiding placeholder when the text box has some value

#inp:not(:empty) + #placeholder
{
	display:none;
}

The above css rule tells that when the input box (div#inp) is not empty i.e has some value inside it then hide the div#placeholder adjacent element of the input box.

+ is adjacent sibling selector.

Here comes the main css part

#inp:not(:empty)
{
	display: inline-block;
	border-bottom-color:#000;
}

Above css rule tells that if the input box (div#inp) is not empty i.e have some value inside it, then set its width equal to the width of the text inside it and change the bottom border color to black.

As we will be typing in the text box width of the text box will increase and it's bottom border become visible which was invisible because it has white color initially and it gives the illusion that a black bar is increasing along with the text.

NOTE -> :not(:empty) css selector is not widely supported across all the browsers.

Write comments