Home > Net >  How to add transition effect to a flex item that has max-width set, and width changes is controlled
How to add transition effect to a flex item that has max-width set, and width changes is controlled

Time:10-29

In the below example the child width grows with smooth transition, but the parent width is abruptly changed!

I want both the child width and parent width transition smoothly.

*note the parent has max-width specified, but rest it controlled by the content, which is the child.

I tried adding transition ease property to the parent div, and expecting that the width change due to the child will smoothly transition here as well.

please check https://codepen.io/abstrekt/pen/qBKdPZe

<div >
    <div >this is the child</div>
</div>

<style>
    .parent {
        padding: 8px;
        display: inline-flex;
        border: 2px solid red;
        max-width: 300px;
        transition: width 1s ease;
    }

    .child {
        white-space: nowrap;
        overflow: hidden;
        border: 2px solid green;
        transition: width 1s ease;
        width: 20px;
    }

    .parent:hover>.child {
        width: 100%
    }
</style>

I've been looking around for answer, but not able to find one for my usecase.

CodePudding user response:

.parent {
    padding: 8px;
    display: inline-flex;
    border: 2px solid red;
    width: 50px;
    max-width:300px;
    transition: width 1s ease;
   
    
}

.parent:hover{ width:100% }

**Just add the initial width property to parent div ** codepen - { https://codepen.io/narut-o/pen/VwdLMEK }

CodePudding user response:

Transitions to auto widths (the parent) have been an issue for a while.

Instead you could apply the transition on max-width instead. You would have to make an approximation on the size of the content. Any value larger then the content width would work.
Values to large will speed up the animation though.

.parent:hover>.child {
  max-width: 150px;
}

.child {
  white-space: nowrap;
  overflow: hidden;
  border: 2px solid green;
  transition: max-width 1s ease;
  max-width: 50px;
}

.parent:hover>.child {
  max-width: 150px;
}

.parent.to-small:hover>.child {
  max-width: 70px;
}

.parent.to-large:hover>.child {
  max-width: 100vw;
}

.parent {
  padding: 8px;
  display: inline-flex;
  border: 2px solid red;
  max-width: 300px;
}

.child {
  white-space: nowrap;
  overflow: hidden;
  border: 2px solid green;
  transition: max-width 1s ease;
  max-width: 50px;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100vw;
  height: 100vh;
}
<div >
  <div >this is the child</div>
</div>

<div >
  <div >to small: this is cut off</div>
</div>

<div >
  <div >to large: this is to fast</div>
</div>

  • Related