How can I simulate a placeholder using a label?

11

I'm trying to make label simulate a fixed placeholder.

The biggest difficulty is to change the properties of label when input gets focus , and input fill in the rest of the space automatically.

I tried to use the same technique as float:left with overflow:hidden , but it did not work.

Would you like to do this using only CSS?

HTML

<article>
  <form>
    <label>Qualquer nome para qualquer tamanho</label>
    <input>
  </form>
</article>

CSS

*{
  margin: 0;
  padding: 0;
}
body{
  font-family: arial;
}
article{
  margin: 5% 0 0 4%;
  width: 50%;
}
label{
  float: left;
  padding: 2%;
  background: #ccc;
  line-heigt: 0;
  font-size: 1em;
  border-radius-right: 3px;
}
form{
  width: 100%;
}
input{
  display: block;
  padding: 2%;
  overflow: hidden;
  border: 0;
  background: #ccc;
  font-family: arial;
  font-size: 1em;
  outline: none;
}
input:focus{
  background: #999;
}

Code not CodePen

    
asked by anonymous 01.01.2014 / 21:45

2 answers

11

Adjacent complex selectors can be used, since both elements ( input and label ) share the same parent element: form . However, there is a single, simple condition: input must precede label .

In this case, you can choose between using the Adjacent sibling selector and Adjacent general selector (~) . The difference between the two is that the adjacent general is more flexible about the position of the child element after his brother. If it sounds confusing, I've written a very thorough article on how the selectors work.

Despite the flexibility of the general adjacent selector (CSS3), I usually opt for the adjacent sibling selector, because it is CSS 2.1. The solution is simple:

input:focus, input:focus + label {
  /* estilo */
}

And the positioning problems caused by the "condition" can be solved with the float property.

View the result in JSBin , where I simplified and organized the solution.

    
11.01.2014 / 22:29
7

I'm not seeing how to do this with CSS only since you want to change one element when you make focus on the other and they are not related to each other.

So my suggestion is to use javascript. Here's an example if you have a library like jQuery or Mootools > I can adapt the code for this library.

var label = document.getElementsByTagName('label')[0];
var input = document.getElementsByTagName('input')[0];

label.onclick = function () {
    label.style.display = 'none';
    input.focus();
};
input.onblur = function () {
    if(!this.value) label.style.display = 'block';
};

Example

    
01.01.2014 / 23:38