Input placeholder using CSS only

Akki619 picture Akki619 · Aug 20, 2013 · Viewed 58.8k times · Source

I know there are lot's of questions regarding this query here but none of them provide the solution for me.

HTML

<input id="tb1" type="text" class="note" />

<br>

<p class="note1"> This is not done.</p>

CSS

p.note1:before{
    content: "Note:";
}

tb1.note:before{
    content: "Enter your number";
}

I am trying with above code and the variation as found on the web but none seems to work for input tag. It's working for p tag.

EDIT: I can't add value attribute to input tag and manage css for the desired result. It's the limitation of the system.

EDIT2: Forget about my css, is there any way that placeholder text is possible without using placeholder attribute and just with plain css for input type="text"

Answer

Hashem Qolami picture Hashem Qolami · Aug 20, 2013

:before creates a pseudo-element that is the first child of the element matched.

The selected element MUST be a container tag. An empty tag like <input> doesn't have any children element.

If you can't edit your HTML code manually, you're still able to that by using JavaScript:

document.getElementById("tb1").setAttribute("placeholder", "Enter your number");

Update

If you want to achieve this by using CSS only, you need to have a container element wrapping your <input> (or come after it).

BUT It doesn't work correctly as placeholder do. You'll not able to check the value of <input> by CSS. If you write something inside the <input>, after blur event, the generated placeholder will be displayed over the <input> again.

HTML:

<label>
    <input id="tb1" type="text" class="note">
</label>

CSS:

label {
  position: relative;
}

label:after {
  content: 'Enter your number';
  position: absolute;
  left: 5px;
  top: 0;
  color: #bbb;
}

#tb1 {
  position: relative;
}

#tb1:focus {
  z-index: 10;
}

JSBin Demo