JSFiddle - React, Tailwind, and code Playground
by the94air
HTML
<main style="width: 300px;margin-top: 4rem;margin-right: auto;margin-left: auto">
<div class="relative">
<input type="text" name="" id="name">
<label for="name">Name</label>
</div>
<div class="relative">
<input type="text" name="" id="email">
<label for="email">Email</label>
</div>
<div class="relative">
<input type="text" name="" id="subject">
<label for="subject">Subject</label>
</div>
<div class="relative">
<input type="text" name="" id="message">
<label for="message">Message</label>
</div>
</main>
CSS
.relative {
position: relative;
margin-bottom: 1rem;
}
input {
width: 100%;
display: block;
}
input + label {
position: absolute;
top: 5px;
font-size: 1rem;
transition: all easy 100ms;
}
input:focus + label {
top: -20px;
font-size: 0.7rem;
}
JavaScript
let fields = document.querySelectorAll("main input[type='text']");
for (var i = 0; i < fields.length; i++) {
fields[i].addEventListener('focusout', (e) => {
let field = e.target;
let label = field.nextElementSibling;
if (field.value !== '') {
label.style.top = '-20px';
label.style.fontSize = '0.7rem';
} else {
label.style.top = null;
label.style.fontSize = null;
}
});
}