Pure HTML + CSS to achieve input placeholder transition effect

The front end of the record uses pure HTML + CSS to realize the transition effect of the "placeholder" prompt text of the input input box moving up and down : (the prompt text here is not the value provided by the placeholder attribute )

renderings

 main code

HTML:

<body>
  <div class="from">
    <div class="from-item">
      <!-- 要给 input 添加 required 属性 -->
      <input class="input" type="text" required>
      <span class="placeholder">用户名</span>
    </div>
  </div>
</body>

 CSS:

<style>
    body {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100vh;
      overflow: hidden;
    }

    .from {
      width: 300px;
      height: 200px;
      margin: 50px auto 0;
      padding: 10px 20px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
    }

    .from-item {
      width: 100%;
      height: 45px;
      margin-top: 50px;
      /* input 和 span 的父盒子要设置相对定位,因为 span 需要使用定位来调整位置 */
      position: relative;
    }

    .input {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
      outline: none;
      border: 0;
      padding: 0 10px;
      border-radius: 10px;
      border: 1px solid #ccc;
      font-size: 16px;
    }

    .input:valid,
    .input:focus {
      border: 2px solid #49bcea;
    }

    /* 给 input 添加 required 属性后,如果输入框中的值是合法的则 .input:valid 选择器样式生效 */
    .input:valid~.placeholder,
    .input:focus~.placeholder {
      top: -35%;
      left: 0;
      color: #49bcea;
    }

    /* span 提示文本默认的位置处于 input 框中充当 placeholder 的效果 */
    .placeholder {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      left: 10px;
      /* 让元素不可点击 */
      pointer-events: none;
      /* 添加过渡时间 */
      transition: all 0.3s;
    }
  </style>

Core summary:

The pointer-events: none; style of CSS can make an element unclickable without responding to the click event, so that when it acts as an input placeholder, it will not affect the normal click of the input to get the focus event;

After the required attribute is added to the input element , if the value in the input box is legal , the .input:valid selector in CSS  can be matched.

Guess you like

Origin blog.csdn.net/qq_43551801/article/details/128280063