Search code examples
htmlcsswidthtransition

Override width of part of my CSS vertical accordeon


I wanted to create a pure CSS vertical accordeon with 3 divs, with the middle one always keeping its width (40%). In the initial state, my 3 divs have to be like this :

  • First div : 30% of width
  • Second div : 40% of width
  • Last div : 30% of width

When the first or the last div is hovered, it must expand to a width of 58%.

However, the last div don't expand like I want, due to the initial width of my item set to 30%:

body {
  margin: 0;
  height: 100%;
}

.donslide {
  display: table;
  width: 100%;
  height: 400px;
}

.donslide .item {
  display: table-cell;
  background: #ddd;
  width: 30%;
  transition: 0.6s ease-in-out all;
  overflow: hidden;
  position: relative;
}

.center {
  display: table-cell;
  width: 40%;
  background: black;
}

.item:hover {
  width: 58%;
}
<div class="donslide">
  <div class="item"></div>
  <div class="center"></div>
  <div class="item"></div>
</div>

If I remove the width setting of my item, everything works like a charm but the transition :

body {
  margin: 0;
  height: 100%;
}

.donslide {
  display: table;
  width: 100%;
  height: 400px;
}

.donslide .item {
  display: table-cell;
  background: #ddd;
  transition: 0.6s ease-in-out all;
  overflow: hidden;
  position: relative;
}

.center {
  display: table-cell;
  width: 40%;
  background: black;
}

.item:hover {
  width: 58%;
}
<div class="donslide">
  <div class="item"></div>
  <div class="center"></div>
  <div class="item"></div>
</div>

How can I make my accordeon work while keeping the sweet transition?


Solution

  • Flex box is the your savior, you can take advantage of the flex-grow property to get the desired effect

    See code snippet

    body {
      margin: 0;
      height: 100%;
    }
    
    .donslide {
      display: flex;
      width: 100%;
      height: 400px;
    }
    
    .donslide .item {
      background: #ddd;
      transition: 0.6s ease-in-out all;
      overflow: hidden;
      width: 0%;
      flex-grow:1;
    
    }
    
    .center {
      width: 40%;
      background: black;
    }
    
    .item:hover {
      width: 60%;
    }
    <div class="donslide">
      <div class="item"></div>
      <div class="center"></div>
      <div class="item"></div>
    </div>