Home > Software engineering >  Container with lots of content starts at a specific height, grows to fit content, and then shrinks o
Container with lots of content starts at a specific height, grows to fit content, and then shrinks o

Time:10-04

I am trying to make a container that holds some text and images, and starts out at a certain size, say 48px. Upon clicking I want the container to grow to fit the contents, and on a second click reshrink down to 48px. The main issue is I don't want to set the height for the full size container, I would like the container to automatically resize to fit the content.

I have figured out how to start the blog at full size, shrink and regrow, but I can't figure out a way to have it start small, grow, and shrink again.

const hoistingId = document.getElementById('hoisting')

function enlargeBlogItem() {
    if(hoistingId.style.height===''){
        hoistingId.style.height = '3rem';
    } else {
        hoistingId.style.height = '';
    }
}

hoistingId.addEventListener('click', enlargeBlogItem)

CodePudding user response:

You can use overflow: hidden; on the parent element to ensure that the child elements are inside the parent and not overlapping and then use a JavaScript function to handle the size changes. Attribute attr-small is used to store the original value of height. By removing the height attribute from the style of the parent it will default to wrapping the children.

function toggleSize(el){

  const originalSize = el.getAttribute('attr-small');
  
  if(el.style.height === originalSize) {
    el.style.removeProperty('height');
  } else {
    el.style.height = originalSize;
  }
}
#container {
  border: 1px solid;
  width: 200px;
  overflow: hidden;
}

#container:hover {
  cursor: pointer;
}

.foo {
  width: 90px;
  height: 90px;
  background-color: red;
  display: inline-block;
  margin-left: 5px;
  margin-top: 5px;
}
<div id='container' onclick='toggleSize(this)' attr-small='48px' style='height:48px;'>
  <div class='foo'></div>
  <div class='foo'></div>
  <div class='foo'></div>
  <div class='foo'></div>
  <div class='foo'></div>
  <div class='foo'></div>
</div>

  • Related