0

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 class="parent">
    <div class="child">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.

2 Answers2

1

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 class="parent">
  <div class="child">this is the child</div>
</div>

<div class="parent to-small">
  <div class="child">to small: this is cut off</div>
</div>

<div class="parent to-large">
  <div class="child">to large: this is to fast</div>
</div>
Lars
  • 3,022
  • 1
  • 16
  • 28
0
.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

Esset
  • 916
  • 2
  • 15
  • 17
Naruto
  • 1
  • 1
  • In my use-case I can't add initial width because it has dynamic content, i.e take any width as the content, just don't exceed max-width. – Samiran Konwar Oct 28 '22 at 12:35