0

I am trying to add some simple animation to a label so when you click in the form field the label slides up - much like a Material Design animation effect.

The issue I have is that we are using a Hubspot form thats pulled into the page so I actually have no control on the markup.

Before I go asking our front end devs im just wondering if this is actually possible with plain CSS?

This is basically how the code looks for the form:

<div class="hs-firstname">
<label>Enter First Name</labe>
<div class="input">
<input class="hs-input firstname"/>
</div>
</div> 

so would naturally think to try something like:

input{position:relative;}
label{position:absolute; top:0; left:0; font-size:18px; transition: all 0.2s ease-in-out;}
input:focus ~ label{top:-15px; font-size:12px;}

The issue is the nesting of the input field inside its own div, which again is something out of my control.

otherwise this would be straightforward.

So just wondering if anyone might know a way around this with Pure CSS or if is does indeed need some react.js (which the page is built in)

Thanks in advance

Jools
  • 81
  • 1
  • 12

2 Answers2

0

Your HTML would need to look like the following to make this work:

.hs-firstname {
  position: relative;
}

label {
  position: absolute;
  top: 0;
  left: 0;
  font-size: 18px;
  transition: all 0.2s ease-in-out;
}

input:focus ~ label {
  top: -15px;
  font-size: 12px;
}
<div class="hs-firstname">
  <input id="firstname" class="hs-input firstname" />
  <label for="firstname">Enter First Name</label>
</div>

Notice the label must be a sibling of the input and must be after the input for the sibling selector to work. You could implement this with JavaScript though.

James Coyle
  • 9,922
  • 1
  • 40
  • 48
0

use this structure and code like this,

In @James Coyle answer, If you click on Label it will not work

.hs-firstname {
  position: relative; 
  margin-top: 50px;
}

input {
  position: relative;
  z-index: 2;
  background: transparent;
  padding: 2px 5px;
  border: 1px solid #999;
}
label {
  position: absolute;
  top: 0;
  left: 5px;
  font-size: 18px;
  transition: all 0.3s ease-in-out;
  z-index: 1;
}

input:focus + label {
  top: -18px;
  font-size: 14px;
}
<div class="hs-firstname">
  <input class="hs-input firstname" />
  <label>Enter First Name</label>
</div>
Atul Rajput
  • 4,073
  • 2
  • 12
  • 24
  • Why are you messing with the z-index? You either need to provide a `for` attribute for the `label` (recommended), or alternatively set `pointer-events: none` on the label. – James Coyle Jun 03 '19 at 09:31
  • yeah, That's also a possible solution. but as he said He can not change the HTML, So I did this... – Atul Rajput Jun 03 '19 at 09:39