Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transition child width 100% when parent width changes

Tags:

html

css

I am having issues coming up with a way to make a child have transitionable width while making the parent change instantaneously.

Using the following example:

.parent {
  height: 100px;
  width: 25%;
  background-color: blue;
}

.child {
  width: 100%;
  transition: width 1s;
  background-color: red;
  height: 50px;
}

.parent:hover {
  width: 50%;
}
<div class="parent">
  <div class="child">
  </div>
</div>

When .parent is hovered, its width should increase, and then the child should take 1s to catch up to the parents width.

Is there any way to achieve this? I don't want the parent to transition as it will cause a lot of jumping around as the parent grows instead of moving everything at once.

like image 776
Matthew Weeks Avatar asked May 22 '26 11:05

Matthew Weeks


1 Answers

You can't use transition, since the child's width value doesn't actually change - it was 100% before and 100% after.

In this case you can use an animation that will start from 50% if the new width, and proceed to the 100%. If the hover ends, the child width will go back to the parent's width immediately.

.parent {
  height: 100px;
  width: 25%;
  background-color: blue;
}

.child {
  width: 100%;
  background-color: red;
  height: 50px;
}

.parent:hover {
  width: 50%;
}

.parent:hover .child {
  animation: 1s both grow;
}

@keyframes grow {
  from { width: 50%; }
  to { width: 100%; }
}
<div class="parent">
  <div class="child">
  </div>
</div>
like image 181
Ori Drori Avatar answered May 24 '26 00:05

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!