Reputation: 530
I read an interesting article the other day and I've been trying to apply it in my workflow.
https://blog.gyrosco.pe/smooth-css-animations-7d8ffc2c1d29#.5a2q978fv
One of the concepts that are mentioned is the idea of only animating elements with opacity and transform. I've been implementing this idea over the last few days and find it pretty awesome.
One issue I've come across is if an element is at opacity 0 the containing parent will still apply the space of the child element. I tried to remove the space with scaling the child element to almost nothing but the space is still persistent.
I was curious if anyone has worked in this manner and has advice on how to animate a parent element to grow with the child element?
function showHiddenBox() {
let hiddenBox = document.querySelector('.hiddenbox')
hiddenBox.setAttribute('data-state', hiddenBox.getAttribute('data-state') === 'hidden' ? 'visible' : 'hidden');
}
.parentbox {
width: 200px;
background-color: #564d49;
}
.showingbox {
display: flex;
align-content: flex-start;
align-items: center;
justify-content: center;
width: 100%;
height: 100px;
background-color: #63cdff;
}
.hiddenbox {
width: 100%;
height: 100px;
transition: all 1s;
background-color: pink;
}
.hiddenbox[data-state="hidden"] {
opacity: 0;
transform: scaleY(.1) translateY(-50px);
transform-origin: top;
}
.hiddenbox[data-state="visible"] {
opacity: 1;
}
<div class="parentbox">
<div class="showingbox">
<button onclick="showHiddenBox()">Click Me</button>
</div>
<div class="hiddenbox" data-state="hidden"></div>
</div>
To further explain myself I've created this snippet. I want to create an animation with just opacity and transform where the brown of the parent element doesn't show but the parent will expand when the child is created.
Upvotes: 1
Views: 282
Reputation: 5732
function showHiddenBox() {
let hiddenBox = document.querySelector('.hiddenbox')
hiddenBox.setAttribute('data-state', hiddenBox.getAttribute('data-state') === 'hidden' ? 'visible' : 'hidden');
}
.parentbox {
width: 200px;
background-color: #564d49;
}
.showingbox {
display: flex;
align-content: flex-start;
align-items: center;
justify-content: center;
width: 100%;
height: 100px;
background-color: #63cdff;
}
.hiddenbox {
width: 100%;
height: 100px;
transition: all 1s;
background-color: pink;
}
.hiddenbox[data-state="hidden"] {
max-height: 0;
transform: scaleY(.1) translateY(-50px);
transform-origin: top;
}
.hiddenbox[data-state="visible"] {
max-height: 300px;
}
<div class="parentbox">
<div class="showingbox">
<button onclick="showHiddenBox()">Click Me</button>
</div>
<div class="hiddenbox" data-state="hidden"></div>
</div>
Use max-height instead of opacity. Over exaggerate the max-height. Depends on how it will work for you. Is this what you want?
Upvotes: 1