Ryan Castle Ryan Castle - 7 months ago 28
HTML Question

CSS - Transitions for numerous auto size containers

I'm currently writing some code for a webpage which displays generated content. The main container, named with the class

block
, holds another container, respectively named
container
. Inside of the container, there are multiple elements, named as
object
.

Both containers have a
height: auto;
CSS setting, as the height depends upon the content inside. The visual effects of this site are something that I am extremely passionate about getting spot on, and I'm wanting to use a transition effect to enable the containers to change height smoothly, rather than instantaneously as it does normally.

Check out this JSFiddle for a code/visual perspective.

Click on the button labelled with 'Add new object' to view the effect that is default. How would I enable a smooth height change of both containers?

Many thanks.

Answer

CSS cannot animate to or from auto values. What you'll need to do is use JavaScript to set the initial height of the .block element and then update it as you add each .object element. Here's an example (apologies for the roughness of it, was a bit pressed for time. It should point you in the right direction, at least):

var	span=document.createElement("span"),
	block=document.querySelector(".block"),
	container=document.querySelector(".container");
span.classList.add("object");
block.style.height=container.offsetHeight+"px";
document.querySelector("body>span").addEventListener("click",function(){
    container.appendChild(span.cloneNode(0));
    block.style.height=container.offsetHeight+"px";
},0);
span {
  position: absolute;
  padding: 5px;
  left: 5px;
  top: 5px;
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.15);
  cursor: pointer;
}
.block {
  position: absolute;
  width: 360px;
  background-color: rgba(255, 0, 255, 0.1);
  left: 50%;
  overflow: hidden;
  top: 50%;
  padding-bottom: 10px;
  margin-left: -200px;
  margin-top: -150px;
  transition:height .25s;
}
.container {
  position: relative;
  width: calc(100% - 40px);
  height: auto;
  min-height: 10px;
  left: 20px;
  top: 5px;
  background-color: rgba(255, 0, 0, 0.15);
  font-size: 0px;
  padding-bottom: 10px;
  transition: 0.25s;
}
.object {
  position: relative;
  width: 80px;
  height: 80px;
  margin: 5px;
  display: inline-block;
  background-color: #f0f;
}
<div class='block'>
  <div class='container'>
    <span class='object'></span>
  </div>
</div>
<span>Add new object</span>

Comments