javascripthtmlcssbootstrap-4material-design

How to create material design input form using css and bootstrap?


I want to design following material design input form using css and bootstrap. Following code is I am currently using. But it doesn't provide exact result I want.

Code Pen Link : View Source Code Here

HTML CODE :

<div class="container">

  <h2>Google Material Design in CSS3<small>Inputs</small></h2>

  <form>

    <div class="group">      
      <input type="text" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>Name</label>
    </div>

    <div class="group">      
      <input type="text" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>Email</label>
    </div>

  </form>

  <p class="footer">
    a <a href="https://scotch.io/tutorials/css/google-material-design-input-boxes-in-css3" target="_blank">tutorial</a> by <a href="https://scotch.io" target="_blank">scotch.io</a>
  </p>

</div>

But I want this design :

enter image description here


Solution

  • 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

    1. position label relative to its container (form-group)
    2. then we specified the top and left positions so that it would land on top of the input field
    3. 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/

    EDIT: Please see my answer below which uses only CSS.