• 纯 CSS 实现搜索框的展示与隐藏


    HTML CSS 实现搜索框的展示与隐藏

    好久没有更新这个动效了, 因为自己没有灵感😶…先看效果
    在这里插入图片描述

    HTML

    主要思路就是默认隐藏输入框, 然后通过 checkbox 选中时展示输入框. 结构如下, 注意标签的顺序因为会使用到 + 这个 CSS 选择器.

    <body>
      <div class="container">
        <label for="toggle">🔍label>
        <input type="checkbox" name="toggle" id="toggle">
        <input type="text" name="search" autofocus class="search">
      div>
    body>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    CSS

    首先是全局样式. 元素水平居中, 背景色为水平渐变

    body {
      display: flex;
      justify-content: center;
      align-items: center;
      background: linear-gradient(90deg, #e74c3c, #9b59b6);
      min-height: 100vh;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    接下来, 设置容器为相对布局, 并隐藏 checkbox 元素.

    .container {
      position: relative;
    }
    .container input[type="checkbox"] {
      display: none;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    设置搜索图标. 这里多说一嘴, 其实这个搜索图标用按钮实现也行, 因为按钮会水平垂直居中咱们的🔍图标. 但是不好的地方是要通过 JS 来设置按钮的点击事件.

    设置 labelabsolute 布局, 其默认 displayinline 所以如果要设置宽高就要将其改为 inline-block

    .container label {
      display: inline-block;
      background-color: #fff;
      height: 50px;
      width: 50px;
      text-align: center;
      line-height: 50px;
      font-size: 24px;
      position: absolute;
      top: 0;
      left: 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    设置搜索框为背景颜色和 border0, 当其处于 focus 状态时取消其 outline.

    📕注意输入框的浏览器默认样式有上下 1px 左右 2px 的内边距(edeg 浏览器), 因此要上下边距为 0, 不然就无法和 label 水平对齐.

    📕默认实现隐藏的方法就是设置 inputlabel 的大小相同, 但因为 label 绝对定位所以 label 占在了 input 的上层显示.

    .container input[type="text"] {
      border: 0;
      font-size: 24px;
      background-color: #fff;
      height: 50px;
      width: 40px;
      padding: 0;
      transition: all .3s ease;
      padding: 0 5px;
    }
    .container input[type="text"]:focus {
      outline: none;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    最后呢, 当 checkbox 处于选中状态时, 要将输入框显示出来, 但是要注意加上 50px 的左外边距, 因为 label 占着位子呢

    .container input[type="checkbox"]:checked + input {
      margin-left: 50px;
      width: 200px;
    }
    
    • 1
    • 2
    • 3
    • 4

    谢谢你看到这里😀

  • 相关阅读:
    Linux学习笔记-Ubuntu系统下配置用户ssh只能访问git仓库
    web前端面试高频考点——Vue原理(diff算法、模板编译、组件渲染和更新、JS实现路由)
    基于SSM的毕业论文答辩系统
    Windows提取环境变量
    redis介绍&了解
    如何实现跨窗口通讯
    MySQL访问和配置
    LeetCode 周赛 344(2023/05/07)手写递归函数的固定套路
    redis运维(十二)
    企业级存储详解与存储资源盘活
  • 原文地址:https://blog.csdn.net/broken_promise/article/details/125981406