如何在CSS中的输入焦点上显示div?

San*_*jay 4 html css

我有一个输入和一个 div,其高度和宽度等于输入的边框底部。我只想显示首先隐藏的div。

.cool{
  font-size: 30px;
  margin: auto;
  outline: none;
  padding-bottom: 0.2em;
  border-width: 0px 0px 2px 0px;
  border-bottom-color: black;
}
div.bar{
  width: 365.3px;
  height: 2px;
  background-color: #42c0fb;
  position: relative;
  top: -2px;
  display: none;
}
input:focus .bar{
  display: block
}
Run Code Online (Sandbox Code Playgroud)
<div style = "margin: auto;">
  <input class = "cool" type = "text" />
  <div class = "bar"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

请帮忙。上面的代码不起作用。

Nis*_*arg 7

当您使用input:focus .bar选择器时,浏览器会在 的.bar后代下搜索input。而.bar是 的兄弟姐妹input

您可以在此处使用同级选择器之一。喜欢:input:focus + .barinput:focus ~ .bar

.cool {
  font-size: 30px;
  margin: auto;
  outline: none;
  padding-bottom: 0.2em;
  border-width: 0px 0px 2px 0px;
  border-bottom-color: black;
}

div.bar {
  width: 365.3px;
  height: 2px;
  background-color: #42c0fb;
  position: relative;
  top: -2px;
  display: none;
}

input:focus + .bar {
  display: block
}
Run Code Online (Sandbox Code Playgroud)
<div style="margin: auto;">
  <input class="cool" type="text" />
  <div class="bar"> Hello</div>
</div>
Run Code Online (Sandbox Code Playgroud)