Home > Mobile >  Move label up to input
Move label up to input

Time:09-28

I need to create an input where label goes up when input is focus/active.

Example

This is the html structure, and i can NOT modify it.

<div >
  <label> Address </label>
<input />
</div>

How can I achieve this without move Label below input element?

CodePudding user response:

Is this what you're looking for?

.form-field:focus-within label {
  display: block;
  margin-bottom: 0.125rem;
}
<div >
  <label> Address </label>
  <input  />
</div>

CodePudding user response:

:focus-within pseudo-class will provide the outcome you are seeking. From the MDN docs linked previously:

The :focus-within CSS pseudo-class matches an element if the element or any of its descendants are focused. In other words, it represents an element that is itself matched by the :focus pseudo-class or has a descendant that is matched by :focus. (This includes descendants in shadow trees.)

Here is a rough example showing the display change when a descendant of .form-field is given focus. This could be improved with more care taken as to the use of the :focus-within selector and perhaps better alignment and animation of the label itself, but nevertheless demonstrates the approach,

.form-field:focus-within {
  /* allows label to be absolute */
  position: relative;
}

.form-field:focus-within label {
  position: absolute;
  /* following values might need adjustment based on existing styles and desired outcome */
  top: -0.5em;
  left: 10px;
  font-size: 12px;
  background: white;
  padding: 0 5px;
}

.form-field:focus-within input {
  /* adjust to suit */
  padding: 8px 5px 5px;
}
<div >
  <label> Address </label>
  <input  />
</div>

  • Related