Axel
Axel

Reputation: 5131

CSS z-index not working in input field

I have an input field with my custom placeholder. I did it custom because of IE & Mozilla issues.

So, basically, there's an input field with an absolute positioned <span> element such that it perfectly fits the input field.

However, when I focus on the input field, the focus goes to the span element. I tried using z-index but it didn't work. Please help. I just want the cursor to focus on input field rather than the span element.

#placeholder {
  position: absolute;
  top: 12px;
  left: 0;
  padding-left: 10px;
  font-size: 11px;
}
<input type="text" style="position: relative;">
<span id="placeholder">Type and Hit Enter to Search...</span>

Upvotes: 2

Views: 3817

Answers (2)

Temani Afif
Temani Afif

Reputation: 273481

Simply use label to wrap both elements. You can also adjust some CSS to make the span disappear on the focus:

label {
  position:relative; /*Make the span positioned relatively to the label*/
}
#placeholder {
  position: absolute;
  top: 4px;
  left: 0;
  padding-left: 5px;
  font-size: 11px;
}

/*On focus change the z-index*/
input:focus + #placeholder {
  z-index: -1;
}
<label>
 <input type="text">
 <span id="placeholder">Type and Hit Enter to Search...</span>
</label>

Upvotes: 2

Andrzej Zi&#243;łek
Andrzej Zi&#243;łek

Reputation: 2319

pointer-events: none is what you need here. It makes element unclickable with pure CSS.

pointer-events method:

#placeholder {
  position: absolute;
  top: 12px;
  left: 0;
  padding-left: 10px;
  font-size: 11px;
  pointer-events: none;
}
<input type="text" style="position: relative;">
<span id="placeholder">Type and Hit Enter to Search...</span>

Fallback alternative for <IE11:

input {
  position: relative;
}

input:hover+span {
  display: none;
}

#placeholder {
  position: absolute;
  top: 12px;
  left: 0;
  padding-left: 10px;
  font-size: 11px;
}
<input type="text" style="position: relative;">
<span id="placeholder">Type and Hit Enter to Search...</span>

Upvotes: 2

Related Questions