Placeholder text in an input field with CSS only (no JavaScript)

∥☆過路亽.° 提交于 2019-12-03 12:53:11
Jay

This is the preferred method, and works in all current browsers:

<input type="text" name="" placeholder="Full Name"/>

This version works for IE9 and before:

<input type="text" name="" value="Full Name" onfocus="value=''" onblur="value='Full Name'"/>
ThinkingStiff

You can do this with a <label> placed behind the index using z-index and a transparent background-color on the <input>. Use :focus to change to a white background.

:first-line has some Firefox issues.

Demo: http://jsfiddle.net/ThinkingStiff/bvJ43/

Note: See code-sushi's comment below for blur issues: Placeholder text in an input field with CSS only (no JavaScript)

Output:

HTML:

<label class="input">enter name<input /><label>​

CSS:

.input {
    color: gray;
    display: block;
    font-size: small;
    padding-top: 3px;
    position: relative;
    text-indent: 5px;
}

input {
    background-color: transparent;
    left: 0;
    position: absolute; 
    top: 0;   
    z-index: 1;
}

input:focus, input:first-line {
    background-color: white;
}

Try this:

HTML

<div>
    <input type="text" id="text"></input>
    <label for="text">required</label>
</div>

CSS

.text-wrapper {
    position: relative;
}
.text-input-label {
    position: absolute;
    /* left and right properties are based on margin, border, outline and padding of the input text field */
    left: 5px;
    top: 3px;
    color: #D1D1D1;
}
#text:focus + label {
    display: none;
}

Working Fiddle

All of the presumably CSS-only answers above have neglected a critical component which is required in order to prevent the label acting as a pseudo-placeholder from "bleeding through" once the user is no longer focused on that particular field.

Hint:

input:valid { background-color:white; }

The pseudo-class :valid obtains whenever a field has any value other than ''. So when your user enters anything in the field of his or her own, the label displayed there will stop being displayed.

Be advised with <input type="email" /> fields, the pseudo-class :valid does and will actually require input of a valid email format (e.g. "xxxx@xxx.com" -- or .net or .org, etc.).

Full instructions how to do this here: http://css-tricks.com/float-labels-css/

Try this: it solves the overflowing placeholder and multi-input cases. The trick is to move the labels behind their inputs and reorder them visually.

You don't need an extra div to achieve what you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!