【问题标题】:Expand search input field while input within a div using CSS 3使用 CSS 3 在 div 中输入时扩展搜索输入字段
【发布时间】:2020-04-20 19:11:39
【问题描述】:

我创建了一个自定义“搜索框”。 “搜索框”实际上是由一个 div 构建的,并在其中输入文本。 稍后我将在左侧添加一个“搜索”图标,在右侧添加一个“清除”按钮。

问题是,div 内的输入已经根据它的容器调整大小,当我关注输入文本时,我找不到扩展父 div(而不是输入本身)的方法。重要的是 div 将展开,以便我稍后添加的图标和按钮 - 将随着输入而展开。 找不到仅使用 CSS(没有 JS)的方法。

感谢您的帮助!

<!DOCTYPE html>
<html>
<head>
<style> 
* {
 box-sizing: border-box;
}

.App {
  width: 100%;
  height: 200px;
  background-color: tan;
}

.fieldcontainer {
  display: flex;

  padding-left: 8px;
  background-color: #CCCCCC;
  border-color: grey;
  width: 300px;
  min-height: 35px;
  align-items: center;
  justify-content: space-between;
  border-radius: 8px;
  cursor: default;
  transition: 'background-color' 0.4s;
}

.fieldcontainer:hover {
  background-color: #C3C3C3;
}

.searchfield {
  background-color: inherit;
  font-size: 1em;
  border: 0;
  flex-grow: 8;
  
  transition: all 0.4s linear;
}

.searchfield:focus {
  outline: none;
  width: 100%;
}

</style>
</head>
<body>

<div class="App">
  <div class="fieldcontainer">
    <input class="searchfield" type="text" placeholder="search" />
  </div>
</div>
</body>
</html>

【问题讨论】:

    标签: html css frontend


    【解决方案1】:

    使用focus-within (https://developer.mozilla.org/fr/docs/Web/CSS/:focus-within)

    * {
      box-sizing: border-box;
    }
    
    .App {
      height: 200px;
      background-color: tan;
    }
    
    .fieldcontainer {
      display: flex;
      padding-left: 8px;
      background-color: #CCCCCC;
      border-color: grey;
      width: 300px;
      min-height: 35px;
      align-items: center;
      justify-content: space-between;
      border-radius: 8px;
      cursor: default;
      transition: 0.4s;
    }
    
    .fieldcontainer:hover {
      background-color: #C3C3C3;
    }
    
    .searchfield {
      background-color: inherit;
      font-size: 1em;
      border: 0;
      flex-grow: 8;
      transition: all 0.4s linear;
      outline:none;
    }
    
    .fieldcontainer:focus-within {
      width: 100%;
    }
    <div class="App">
      <div class="fieldcontainer">
        <input class="searchfield" type="text" placeholder="search" />
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2019-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多