Effortlessly Collapse/Expand Div using Pure CSS

If you're looking for a way to easily collapse and expand a div using only CSS, you're in luck. With a few lines of code, you can create a smooth and responsive animation that will make your website look more professional.

To begin, you'll need to create a div with a unique ID that you can target with your CSS. For this example, we'll use the ID "collapse". Next, you'll need to add a checkbox input element before the div. We'll use this checkbox to toggle the visibility of the div.

Here's the HTML code for the div and checkbox:

<input type="checkbox" id="toggle">
<label for="toggle">Click to expand/collapse</label>
<div id="collapse">
  <p>This is the content that will be collapsed or expanded.</p>

Now, let's add some CSS to make the magic happen. We'll use the :checked pseudo-class to determine whether the checkbox is checked or not, and then use the adjacent sibling selector (+) to target the div that comes after it.

Here's the CSS code:

#collapse {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.5s ease-out;
#toggle:checked + label + #collapse {
  max-height: 1000px;
  transition: max-height 0.5s ease-in;

In this example, we set the initial max-height of the div to 0, and hide any overflow. We also add a transition property to create a smooth animation that lasts 0.5 seconds.

When the checkbox is checked, we use the adjacent sibling selector (+) to target the label and then the div that comes after it. We set the max-height to a large value (1000px), which will cause the div to expand. We also change the transition property to ease-in, which will make the animation appear smoother.

And that's it! With just a few lines of code, you can create a responsive and professional-looking collapse/expand feature for your website.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information