首页 > 解决方案 > How to create text field similar to Material UI text field without using Material UI library?

问题描述

Using pure HTML, CSS, Reactjs

I want to make placeholder to move up to the border when you click on the text field

example for Material UI text field: https://material-ui.com/components/text-fields/

标签: htmlcssreactjsmaterial-ui

解决方案


You can find many alternate options using pure html5 and css.

Following is an example

<div class="form__group">
  <input type="email" id="email" class="form__field" placeholder="Your Email">
  <label for="email" class="form__label">Your Email</label>
</div>

<div class="form__group">
  <textarea id="message" class="form__field" placeholder="Your Message" rows="6"></textarea>
  <label for="message" class="form__label">Your Message</label>
</div>

and css

@import url(https://fonts.googleapis.com/css?family=Roboto);

html {
  font-family: 'Roboto', sans-serif;
}

.form__group {
  position: relative;
  padding: 15px 0 0;
  margin-top: 10px;
}

.form__field {
  font-family: inherit;
  width: 100%;
  border: 0;
  border-bottom: 1px solid #d2d2d2;
  outline: 0;
  font-size: 16px;
  color: #212121;
  padding: 7px 0;
  background: transparent;
  transition: border-color 0.2s;
}

.form__field::placeholder {
  color: transparent;
}

.form__field:placeholder-shown ~ .form__label {
  font-size: 16px;
  cursor: text;
  top: 20px;
}

label,
.form__field:focus ~ .form__label {
  position: absolute;
  top: 0;
  display: block;
  transition: 0.2s;
  font-size: 12px;
  color: #9b9b9b;
}

.form__field:focus ~ .form__label {
  color: #009788;
}

.form__field:focus {
  padding-bottom: 6px;
  border-bottom: 2px solid #009788;
}

as given in this example here


推荐阅读