Accordion-like Expanding Card With JavaScript And CSS

Category: Accordion , Javascript | April 14, 2022
Author:SayanBarcha
Views Total:748 views
Official Page:Go to website
Last Update:April 14, 2022
License:MIT

Preview:

Accordion-like Expanding Card With JavaScript And CSS

Description:

Cards are trending in web design as they offer a quick and easy way to display information.

Using only HTML and CSS, you can create an accordion-like effect with expanded/collapsed card content.

This functionality can be helpful in designing layouts for articles and blog posts on your website.

How to use it:

1. Add content and background images to the cards.

<div class="panel active" style="background-image: url('1.jpg');">
  <h3>CSSScript.com</h3>
</div>
<div class="panel" style="background-image: url('2.jpg');">
  <h3>CSSScript.com</h3>
</div>
<div class="panel" style="background-image: url('3.jpg');">
  <h3>CSSScript.com</h3>
</div>
<div class="panel" style="background-image: url('4.jpg');">
  <h3>CSSScript.com</h3>
</div>
<div class="panel" style="background-image: url('5.jpg');">
  <h3>CSSScript.com</h3>
</div>

2. The primary CSS styles for the expanding cards.

.panel{
  background-size: auto 100%;
  background-position: center;
  background-repeat: no-repeat;
  height: 400px;
  border-radius: 10px;
  color: #fff;
  cursor: pointer;
  flex: 0.5;
  margin: 10px;
  position: relative;
  transition: flex 0.7s ease-in;
}
.panel h3{
  font-size: 24px;
  position: absolute;
  bottom: 20px;
  left: 20px;
  margin: 0;
  opacity: 0;
}
.panel.active{
  flex: 5;
}
.panel.active h3{
  opacity: 1;
  transition: opacity 0.3s ease-in 0.4s;
}

3. Hide certain cards on small screen devices.

@media(max-width: 480px){
  .container{
    width: 100vw;
  }
  .panel:nth-of-type(4),
  .panel:nth-of-type(5){
    display: none;
  }
}

4. Enable the accordion expanding effect and add the active class to the card you’re viewing on.

let panels =document.querySelectorAll('.panel')
panels.forEach(panel => {
  panel.addEventListener('click', () =>{
    removeActiveClasses()
    panel.classList.add('active')
  })
})
function removeActiveClasses(){
  panels.forEach(panel => {
    panel.classList.remove('active')
  })
}

You Might Be Interested In:


Leave a Reply