CSS Transition expands and collapses elements by changing the Height

CSS Transition expands and collapses elements by changing the Height

A common development need is that we want to collapse part of an element until it is needed. Some common frameworks, such as Bootstrap and JQuery, provide transition effects. However, CSS Transition gives us a lot of flexibility in terms of transitioning heights. Therefore, you don't have to include additional frameworks in your project.
Next, let’s take a look at how to use CSS Transition to animate the height property, as well as the problems and solutions.
You can check the effect in 👉

Transition height

What we want to achieve is that when clicking the View More button, the height of the element will increase to show all the content of the article, and when clicked again, it will shrink back to its original size.
We will create a CSS class for this. This class is added to the <article> element using JavaScript when the view more button is clicked.
First, we'll add a <div> element to our HTML file and give it some content.

<article id="article">
  <h3>Use CSS Transition to expand and collapse elements by changing the Height</h3>
  <p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Illo perspiciatis tempora iure accusamus rerum. Fully porro unde, laboriosam soluta accusantium numquam quos adipisci commodi velit, expedita officia cum excepturi molestias.</p>

  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab doloribus optio, eaque harum blanditiis totam voluptatibus amet quibusdam veritatis animi ipsum eveniet modi aspernatur, vel repellat est commodi consequatur unde! A obcaecati soluta inventore, numquam impedit quaerat magnam incidunt sit cupiditate sequi cum. Exercitationem commodi reiciendis culpa iste optio aliquam incidunt at, ab consectetur quae est sapiente dignissimos, sit deleniti voluptatibus animi repudiandae. Itaque nemo laborum dolore numquam repudiandae mollitia quis. Placeat quis architecto eligendi distinctio quas perferendis officia voluptatem illo, nisi ullam voluptatum odio eveniet non eum vero vel dolorum deleniti adipisci culpa. Reprehenderit cum ut voluptates reiciendis iusto.</p>

  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab doloribus optio, eaque harum blanditiis totam voluptatibus amet quibusdam veritatis animi ipsum eveniet modi aspernatur, vel repellat est commodi consequatur unde! A obcaecati soluta inventore, numquam impedit quaerat magnam incidunt sit cupiditate sequi cum. Exercitationem commodi reiciendis culpa iste optio aliquam incidunt at, ab consectetur quae est sapiente dignissimos, sit deleniti voluptatibus animi repudiandae. Itaque nemo laborum dolore numquam repudiandae mollitia quis. Placeat quis architecto eligendi distinctio quas perferendis officia voluptatem illo, nisi ullam voluptatum odio eveniet non eum vero vel dolorum deleniti adipisci culpa. Reprehenderit cum ut voluptates reiciendis iusto.</p>

  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ab doloribus optio, eaque harum blanditiis totam voluptatibus amet quibusdam veritatis animi ipsum eveniet modi aspernatur, vel repellat est commodi consequatur unde! A obcaecati soluta inventore, numquam impedit quaerat magnam incidunt sit cupiditate sequi cum. Exercitationem commodi reiciendis culpa iste optio aliquam incidunt at, ab consectetur quae est sapiente dignissimos, sit deleniti voluptatibus animi repudiandae. Itaque nemo laborum dolore numquam repudiandae mollitia quis. Placeat quis architecto eligendi distinctio quas perferendis officia voluptatem illo, nisi ullam voluptatum odio eveniet non eum vero vel dolorum deleniti adipisci culpa. Reprehenderit cum ut voluptates reiciendis iusto.</p>
</article>
<button id="seeMoreBtn">See more</button>

The CSS styles are as follows:

article {
  max-width: 800px;
  height: 300px;
  overflow-y: hidden;
}

/* Add this class when the button is clicked */
article.extended {
  height: 628px;
}

button {
  padding: .6rem;
}

The JavaScript is as follows:

const seeMore = document.getElementById('seeMoreBtn')
const article = document.getElementById('article')

seeMore.addEventListener('click', () => {
  article.classList.toggle('extended')

  const extended = article.classList.contains('extended')
  if (extended) {
    seeMore.innerHTML = 'Collapse content'
  } else {
    seeMore.innerHTML = 'See more'
  }
})

Add CSS transition properties to the article so that the content can slide up and down smoothly when the button is clicked.

article {
  max-width: 800px;
  height: 300px;
  overflow-y: hidden;
  transition: height 0.4s linear;
}

Now apply it to your article, you can see that it can slide up and down smoothly, it is simple and convenient, but this method has limitations. Let’s take a look below.

limit

This limitation is whether the height is known. In the above example, we clearly know the height of the article, and it works very well, but when we are dealing with dynamic content, we don’t know the height of the element, and its height may also change with the screen size or other means.
In fact, the solution is very simple. For dynamic content, the height of the element should be set to auto. This way, any increase or decrease in the element's height will adapt. But there will be another problem: when the height of the element is set to auto, CSS transition will not work.
The good news is that there is a way to fix this problem without having to resort to more JavaScript.

Solution

The solution is to convert the max-height property instead of the height property. First, we have to estimate the maximum height our element can reach. Then, when the element expands, we set the element's max-height to be larger than our estimate.
We change the height property to max-height:

article {
    max-width: 800px;
    max-height: 300px;
    overflow-y: hidden;

    /* Increase transition time to adjust to height */
    transition: max-height 0.7s linear;
}

article.expanded {
    max-height: 1500px;
}

This way the animation works and we still get the effect we want. The transition time may need to be adjusted depending on the effect you want.

This is the end of this article about how to expand and collapse elements by changing the height of CSS Transition. For more information about expanding and collapsing elements with CSS Height, please search previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

<<:  Problems encountered when updating the auto-increment primary key id in Mysql

>>:  In-depth understanding of the specified IE browser rendering method

Recommend

Quickly solve the problem of slow Tomcat startup, super simple

Today I helped a classmate solve a problem - Tomc...

How does MySQL ensure data integrity?

The importance of data consistency and integrity ...

MySQL lock control concurrency method

Table of contents Preface 1. Optimistic Locking A...

How to implement the webpage anti-copying function (with cracking method)

By right-clicking the source file, the following c...

Detailed tutorial on running multiple Springboot with Docker

Docker runs multiple Springboot First: Port mappi...

Vue computed properties

Table of contents 1. Basic Examples 2. Computed p...

How to modify the contents of an existing Docker container

1. Docker ps lists containers 2. Docker cp copies...

Two problems encountered when deploying rabbitmq with Docker

1. Background The following two problems are enco...

Detailed explanation of the basic functions and usage of MySQL foreign keys

This article uses examples to illustrate the basi...

Detailed explanation of Linux text processing command sort

sort Sort the contents of a text file Usage: sort...