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

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


POPMUISE
浏览 33回答 1
1回答

海绵宝宝撒

使用focus-within(https://developer.mozilla.org/fr/docs/Web/CSS/:focus-within)* {&nbsp; box-sizing: border-box;}.App {&nbsp; height: 200px;&nbsp; background-color: tan;}.fieldcontainer {&nbsp; display: flex;&nbsp; padding-left: 8px;&nbsp; background-color: #CCCCCC;&nbsp; border-color: grey;&nbsp; width: 300px;&nbsp; min-height: 35px;&nbsp; align-items: center;&nbsp; justify-content: space-between;&nbsp; border-radius: 8px;&nbsp; cursor: default;&nbsp; transition: 0.4s;}.fieldcontainer:hover {&nbsp; background-color: #C3C3C3;}.searchfield {&nbsp; background-color: inherit;&nbsp; font-size: 1em;&nbsp; border: 0;&nbsp; flex-grow: 8;&nbsp; transition: all 0.4s linear;&nbsp; outline:none;}.fieldcontainer:focus-within {&nbsp; width: 100%;}<div class="App">&nbsp; <div class="fieldcontainer">&nbsp; &nbsp; <input class="searchfield" type="text" placeholder="search" />&nbsp; </div></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5