CSS -在移除子元素时动画父元素的宽度



我有一个div容器内的伸缩容器设置最大宽度。当移除子元素时,宽度将减小。它是可能的动画宽度变化与仅仅CSS?

function remove(el) {
var element = el;
element.remove();
}
#flex {
display: flex;
}
#parent {
max-width: 200px;
background: blue;
border: 2px solid green;
height: 100px;
width: auto;
}
#child {
width: 100px;
height: 100px;
background: red;
}
#other {
flex: 1;
height: 100px;
background: yellow;
}
<div id="flex">
<div id="parent">
<div id="child" onclick="remove(this)">
</div>
</div>
<div id="other">
</div>
</div>

你不能用纯CSS。动画是基于宽度的变化,所以你需要通过Javascript设置#child的宽度为0。要完全去除#child,可以用setTimeout延缓。

function remove(el) {
var element = el;

el.style.width = 0; //trigger the animation with width changes

setTimeout(() => {
element.remove();
}, 500); //0.5 seconds
}
#flex {
display: flex;
}
#parent {
max-width: 200px;
background: blue;
border: 2px solid green;
height: 100px;
width: auto;
}
#child {
width: 100px;
height: 100px;
background: red;
transition: width 0.5s; /* Width animation in 0.5 seconds */
}
#other {
flex: 1;
height: 100px;
background: yellow;
}
<div id="flex">
<div id="parent">
<div id="child" onclick="remove(this)">
</div>
</div>
<div id="other">
</div>
</div>