JianYA JianYA - 1 month ago 10
CSS Question

CSS hover to expand inputbox and pause to allow input

I am trying to learn how I can hover over a search icon which then expands the inputbox which will allow a user to enter some details in. So far I have found a css solution for the hover but it doesn't seem to work. Is there a better way to do this? Please help.

This is the jsfiddle
https://jsfiddle.net/amosangyongjian/xzo0kaj5/

This is the html/css that doesn't seem to work

<input type="text" class="search"/>
<span class="searchicon"><i class="fa fa-search"></i></span>

.search{
display:none;
width:0;
transition: width 2s;
}

.searchicon:hover~.search{
display:block;
width:197px;
}

Answer

The ~ selector matches the second element only if it is preceded by the first. To make this work you could put input after the span in the html. I think you may find that only using css to achieve this has its limitations, a better option may be to apply the class using js to show the input so you have more control. I added some additional css selectors (.search:hover, .search:focus) to overcome some of the problems I saw.

.search{
  width:0;
  visibility: hidden; /* display property wasn't working with transition */
  transition: width 2s;
  float: left;
}

.searchicon:hover~.search, .search:hover, .search:focus{
  visibility: visible;
  width:197px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://opensource.keycdn.com/fontawesome/4.6.3/font-awesome.min.css" rel="stylesheet"/>
<span class="searchicon"><i class="fa fa-search"></i></span>
<input type="text" class="search"/>

Basic example for handling with jquery:

$('.searchicon').hover(function() {
  $('.search').addClass('show');  
});
.search{
  width:0;
  visibility: hidden; /* display property wasn't working with transition */
  transition: width 2s;
  float: left;
}

.show {
  visibility: visible;
  width:197px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://opensource.keycdn.com/fontawesome/4.6.3/font-awesome.min.css" rel="stylesheet"/>
<span class="searchicon"><i class="fa fa-search"></i></span>
<input type="text" class="search"/>

Comments