How to animate width on parent element with display:block/none on child elem

Viewed 922

I have two children in one parent element where first child is always visible but second one is visible on hover only. Since I have fit-content set for parent's width when I hover the parent elem expands. What I need is a smooth transition for this expansion. I do all this in React. Thanks

Check context please:

.parent{
  display: flex;
  justify-content: space-evenly;
  background-color: #f31d84;
  width: fit-content;
}
.icon{
  margin: 5px;
}
.text{
  display: none;
  margin: 5px;
}

.parent:hover .text{
  display: block;
}
<div>
  <div class='parent'>
    <div class='icon'>
      icon
    </div>
    <div class='text'>
      texttexttexttext
    </div>
  </div>
</div>

4 Answers

I've managed to find a solution for my problem. The code:

<div>
  <div class='parent'>
    <div class='icon'>
      icon
    </div>
    <div className='text-wrapper'>
      <div class='text'>
        texttexttexttext
      </div>
    </div>

  </div>
</div>

.parent{
  display: flex;
  justify-content: space-evenly;
  background-color: #f31d84;
  width: fit-content;
}
.icon{
  margin: 5px;
}
.text{
  opacity: 0;
  max-width: 0;
  margin: 5px;
  transition: 5s ease;
}
.text-wrapper{
  width: auto;
}

.parent:hover .text{
  opacity: 1;
  max-width: 1000px;
}

You can't animate what is not a value. I mean that going from display: none to display: block can't be animate because they are not values.

It's a wrong implementation. Your parent element width in this example doesn't change on hover. If u want to animate things, a good practice is set width 0 to the child element and when parent element gets hovered div with the class text gets 50% of parent's width. you can achieve this through css only and react way. If u are interested let me know to edit this answer.

Transitioning from display: none to display: block will not work. Indeed, there is only a finite number of CSS properties that can be animated and display is not one (see: Animatable CSS properties on MDN).

The common way to do such a thing is to transition from width: 0 to width: 50% (or whatever value you want your block to be, just remember that auto will not work).

.parent {
  display: flex;
  justify-content: space-evenly;
  background-color: #f31d84;
  width: fit-content;
}

.icon {
  margin: 5px;
}

.text {
  display: block;
  margin: 5px;
  width: 0;
  overflow: hidden;
  transition: all .2s ease;
}

.parent:hover .text {
  width: 50%;
  transition: all .2s ease;
}
<div>
  <div class='parent'>
    <div class='icon'>
      icon
    </div>
    <div class='text'>
      texttexttexttext
    </div>
  </div>
</div>

Related