Sol Sol - 3 months ago 9
CSS Question

How can I make the width transition smooth on hover?

This is probably super simple but I'm completely stuck and I can't find anything helpful. Sorry if this was asked already, if so please link me to it and sorry to have wasted your time.

So, I have this code:



#nav {
position: fixed;
top: 70px;
left: 70px;
}

.button {
position: relative;
background: white;
text-transform: uppercase;
font-size: 11px;
letter-spacing: 2px;
border: 1px solid #eee;
width: 20px;
height: 20px;
line-height: 20px;
}

.button:hover {
width:auto;
}

.text {
overflow: hidden;
}

.icon {
float: left;
margin-right: 5px;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>

<div id="nav">

<div class="button">
<div class="icon"><i class="fa fa-home" aria-hidden="true"></i></div>
<div class="text">home</div>
</div>

</div>





What I'd like to do is:


  1. Get the house symbol inside a square so it looks like a little button. The text "home" shouldn't be visible at all.

  2. Make the whole thing's width expand smoothly when I hover on the house "button" to reveal the text. If possible, I'd like the expanded width to fit the text I get there since I'll have more tabs with different text lengths.



Sorry if this is too much to ask. I'm really stuck with this, as you can see I kind of got the basics working already, all I need is really these two points I listed above. Thank you so much for your help.

Answer

You can center the icon with some left margin and use CSS transitions for the hover effect (see w3schools for some more examples):

#nav {
  position: fixed;
  top: 70px;
  left: 70px;
}
.button {
  position: relative;
  background: white;
  text-transform: uppercase;
  font-size: 11px;
  letter-spacing: 2px;
  border: 1px solid #eee;
  width: 20px;
  height: 20px;
  line-height: 20px;
  -webkit-transition: width 1s;
  transition: width 1s;
}
.button:hover {
  width: 100%;
}
.text {
  overflow: hidden;
}
.icon {
  float: left;
  margin: 0 5px;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" />

<div id="nav">

  <div class="button">
    <div class="icon"><i class="fa fa-home" aria-hidden="true"></i>
    </div>
    <div class="text">home</div>
  </div>

</div>