How to create material design input form using css and bootstrap?
CSS Only solution; use combination of sibling selector ~
on the label and :valid
pseudo selector on the input.
body {
margin: 10px;
}
.form-group>label {
bottom: 34px;
left: 15px;
position: relative;
background-color: white;
padding: 0px 5px 0px 5px;
font-size: 1.1em;
transition: 0.2s;
pointer-events: none;
}
.form-control:focus~label {
bottom: 55px;
}
.form-control:valid~label {
bottom: 55px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<div class="container">
<div class="row">
<div class="col-md-6">
<br>
<div class="form-group">
<input type="text" class="form-control" id="usr" required>
<label for="usr">Name</label>
</div>
<div class="form-group">
<input type="text" class="form-control" id="password" required>
<label for="usr">Password</label>
</div>
</div>
</div>
</div>
Since you've tagged Bootstrap 4, I'm assuming you wanted the solution with regards to that framework.
Setup a default form-group, label, and input markup like this;
<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr">
</div>
Then add this css, what this would do is
- position label relative to its container (form-group)
- then we specified the top and left positions so that it would land on top of the input field
- I added a white background and padding to the label so that it would have a box around the label.
.form-group > label {
top: 18px;
left: 6px;
position: relative;
background-color: white;
padding: 0px 5px 0px 5px;
font-size: 0.9em;
}
Here's a fiddle with that code on bootstrap 4; http://jsfiddle.net/rw29jot4/
For the animation, check this fiddle, we need to utilize click events and move the position of the label;
Updated code with animation; http://jsfiddle.net/sedvo037/