html - 使用CSS 3在div内输入时扩展搜索输入字段

标签 html css frontend

我创建了一个自定义“搜索框”。 “搜索框”实际上是由 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>

最佳答案

使用焦点内 ( 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>

关于html - 使用CSS 3在div内输入时扩展搜索输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61330198/

相关文章:

html - 如何使网页适应放大移动

html - 如果没有更多空间,将文本换行到下一行

html - 将宽度和省略号设置为表格的 <td> 元素

javascript - Document.getElementById() 返回名称等于指定 id 的元素

html - 具有 CSS 网格的可点击图 block

jquery - 使用 jquery 随机化布局

javascript - 使用 jQuery 删除类的正确方法

javascript - 在javascript中将图像添加到数组

html - header.php 背景图像在不同页面上看起来不同。可能是浏览器问题?

javascript - JQuery SlideUp - 图像背后的背景颜色