How can I style individual parts of an input placeholder? [duplicate]

You can’t do that with standard placeholder attribute. I will elaborate on another approach, making custom placeholder with some wrapper around input element.

HTML

<div class="placeholder-wrap">
    <input type="text" name="userName" />
    <span class="placeholder">
        This is a <b class="important">placeholder</b>
    </span>
</div>

CSS:

.placeholder-wrap {
    margin: 20px;
    display: inline-block;
    position: relative;
    background: #FFF;
}
.placeholder-wrap .placeholder {
    position: absolute;
    top: 50%;
    left: 5px;
    color: #888;
    margin-top: -.5em;
    line-height: 1em;
    z-index: 9;
    overflow: hidden;
    white-space: nowrap;
    width: 100%;
}
.placeholder-wrap input {
    background-color: transparent;
    border: 1px #999 solid;
    padding: 4px 6px;
    position: relative;
    z-index: 10;
}
.placeholder-wrap input:focus + .placeholder {
    display: none;
}

Yes, quite a few code, but gives you some flexibility with styling.

Demo: http://jsfiddle.net/dfsq/xD5Lq/

UPD. There is however a problem (thanks @AlexG for reporting). Once the value is entered and the input loses focus, placeholder appears again on top of the value. There are two ways to address this issue. The first one is pure CSS again using :invalid pseudo-class, which would also need required attribute on input:

.placeholder-wrap {
    display: inline-block;
    position: relative;
    background: #FFF;
    overflow: hidden;
}
.placeholder-wrap .placeholder {
    position: absolute;
    top: 50%;
    left: 5px;
    color: #888;
    margin-top: -.5em;
    line-height: 1em;
    z-index: 9;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    width: 100%;
}
.placeholder-wrap input {
    background-color: transparent;
    border: 1px #999 solid;
    padding: 4px 6px;
    position: relative;
    z-index: 10;
}
.placeholder-wrap input:focus + .placeholder,
.placeholder-wrap input[required]:valid + .placeholder,
.placeholder-wrap input.not-empty + .placeholder {
    display: none;
}


input {width: 300px;}
.important {color: brown;}
<p>CSS fix</p>

<div class="placeholder-wrap">
    <input type="text" name="userName" required />
    <span class="placeholder">
        This is a <b class="important">placeholder</b> long text goes here
    </span>
</div>

<p>Javascript fix</p>

<div class="placeholder-wrap">
    <input type="text" name="userName" 
           onchange="this.className = this.value 
             ? this.className + ' not-empty'
             : this.className.replace(/\bnot-empty\b/, '')" 
    />
    <span class="placeholder">
        This is a <b class="important">placeholder</b> long text goes here
    </span>
</div>

Leave a Comment