大家好,我是 Just,这里是「设计师工作日常」,今天分享的是用 css 实现一个动态显示出输入框的动效。

《有趣的css》系列最新实例通过公众号「设计师工作日常」发布。


(目录)

整体效果

利用 flex 布局,然后利用 css 选择器来实现鼠标悬浮、点击等状态的交互效果。

此效果可适用于小表单、或者登录注册表单等场景。


核心代码部分,简要说明了写法思路;完整代码在最后,可直接复制到本地运行。

核心代码

html 代码

<label class="label28">
  <span class="span28">用户名</span>
  <input class="inp28" type="text" required>
</label>

label 搭配 input ,然后 input 设置 required 来判断非空状态。

css 部分代码

.label28{
  width: 190px;
  height: 68px;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  cursor: text;
}
.span28{
  width: 100%;
  color: #000;
  font-size: 14px;
  margin-bottom: 6px;
  padding: 0 10px;
}
.inp28{
  width: 100%;
  padding: 0 10px;
  height: 2px;
  border: 0;
  font-size: 14px;
  box-sizing: border-box;
  background-color: rgba(0,0,0,0.1);
  transition: .3s;
}
.inp28:hover{
  background-color: rgba(50,133,255,0.7);
}
.inp28:focus,.inp28:valid{
  background-color: rgba(50,133,255,0.2);
  border: 2px solid rgba(50,133,255,0.7);
  border-radius: 4px;
  height: 42px;
  color: #000;
}

利用 flex 布局,设置 justify-content: flex-end

通过 :hover:foucus:valid 来判断鼠标状态,然后不同的状态下,输入框的高度变化。

在让输入框变高时,自动撑起提示文本,输入框变化成不同的样式来实现交互的效果。

完整代码如下

html 页面

<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css">
    <title>输入框交互</title>
  </head>
  <body>
    <div class="app">
      <label class="label28">
        <span class="span28">用户名</span>
        <input class="inp28" type="text" required>
      </label>
    </div>
  </body>
</html>

css 样式

/** style.css **/
.app{
  width: 100%;
  height: 100vh;
  background-color: #ffffff;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
.label28{
  width: 190px;
  height: 68px;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  cursor: text;
}
.span28{
  width: 100%;
  color: #000;
  font-size: 14px;
  margin-bottom: 6px;
  padding: 0 10px;
}
.inp28{
  width: 100%;
  padding: 0 10px;
  height: 2px;
  border: 0;
  font-size: 14px;
  box-sizing: border-box;
  background-color: rgba(0,0,0,0.1);
  transition: .3s;
}
.inp28:hover{
  background-color: rgba(50,133,255,0.7);
}
.inp28:focus,.inp28:valid{
  background-color: rgba(50,133,255,0.2);
  border: 2px solid rgba(50,133,255,0.7);
  border-radius: 4px;
  height: 42px;
  color: #000;
}

页面渲染效果

以上就是所有代码,以及简单的思路,希望对你有一些帮助或者启发。


CSS 是一种很酷很有趣的计算机语言,在这里跟大家分享一些 CSS 实例 Demo,为学习者获取灵感和思路提供一点帮助,希望你们喜欢。

我是 Just,这里是「设计师工作日常」,求点赞求关注!