Animate parent div when an input is focused

╄→гoц情女王★ 提交于 2019-12-01 18:37:27

A Pure CSS Solution - Flexbox Order

If you are able to restructure your html a little it's possible by changing the dom so input is 1st in the html but 2nd on screen. This method uses flexbox order to do so.

Here's an example.

.container {
  display: flex;
  flex-direction: column;
}
input {
  display: flex;
  flex-direction: column;
  order: 2;
}
.brandHeader {
  display: flex;
  order: 1;
  transition: all 0.2s ease;
}
input:focus + .brandHeader {
  margin-top: -10px;
}
<form class="container">
  <input type="text" id="search-bar" placeholder="Search">
  <div class="brandHeader">
    <h1>My Header</h1>
  </div>
</form>

fiddle

https://jsfiddle.net/Hastig/djj01x6e/

If that would work for you let me know and I'll explain more about it.


A 2nd Pure CSS Solution - flex-direction: column-reverse

Pretty much the same as the first but no need to use order: x;

.container {
  display: flex;
  flex-direction: column-reverse;
} 
input {
  display: flex;
  flex-direction: column;
 }
.brandHeader {
  display: flex;
  transition: all 0.2s ease;
}
input:focus + .brandHeader {
 margin-top: -10px;
}
<form class="container">
    <input type="text" id="search-bar" placeholder="Search">
    <div class="brandHeader">
      <h1>My Header</h1>
    </div>
</form>

fiddle

https://jsfiddle.net/Hastig/djj01x6e/1/


You can do a similar thing without flexbox using position: absolute to keep input 1st in dom but 2nd on screen but it too depends on your being able to change html structure.

You can toggle or addClass to brandHeader on input:focus with jQuery, then you can add the transition to both h1 and input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!