使用CSS3在div中进行输入时,展开搜索输入字段



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

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

* {
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>

最新更新