htmlcsscss-animationscss-tables

CSS animatable table row width?


Take the following basic CSS table. Is it possible to set a table cell to zero width and have it be animatable via CSS?

The only way I can seem to hide a table cell is to use display: none, but that isn't animatable. Is this possible?

.table {
  display: table;
  width: 100%;
}
.row {
  display: table-row;
}
.cell {
  display: table-cell;
  outline: 1px solid #000;
  text-align: center;
  transition: width 0.5s ease;
}
.left,
.right {
  width: 50%;
}
.center {
  width: 0%;
}
@media (min-width: 480px) {
  .left,
  .right,
  .center {
    width: 33.333%;
    color: red;
  }
}
<div class='table'>
  <div class='row'>
    <div class='cell left'>left</div>
    <div class='cell center'>center</div>
    <div class='cell right'>right</div>
  </div>
</div>

Here is a JSFiddle link.


Solution

  • Animated table cell width changes

    The magic sauce is to use table-layout: fixed on the table.

    The width of the cell is changed to 0% or 0px — The length type used to shrink the cell must be the same as the length type used for the normal cell width. In the example below the normal width is 33%, so the width changes to 0%.

    Transition example

    If the animation is used to simply hide a table cell when the user interacts with it in some way, a transition property on the cells is all you need:

    .table {
      display: table;
      width: 100%;
      table-layout: fixed;
    }
    .row {
      display: table-row;
    }
    .cell {
      display: table-cell;
      outline: 1px solid #000;
      text-align: center;
      width: 33%;
      overflow: hidden;
      transition: width .4s;
    }
    .table:hover .center {
      width: 0%
    }
    <div class='table'>
      <div class='row'>
        <div class='cell'>left</div>
        <div class='cell center'>center</div>
        <div class='cell'>right</div>
      </div>
    </div>

    Animated example using keyframes

    This method can also be used to manipulate the width of table cells in an animation:

    .table {
      display: table;
      width: 100%;
      table-layout: fixed;
    }
    .row {
      display: table-row;
    }
    .cell {
      display: table-cell;
      outline: 1px solid #000;
      text-align: center;
      width: 33%;
      overflow: hidden;
      transition: width .4s;
    }
    .center {
      animation: reduceWidth 5s infinite;
    }
    @keyframes reduceWidth {
      0%, 100% {
        width: 33%;
        background: #F00;
      }
      50% {
        width: 0%;
        background: #000;
      }
    }
    <div class='table'>
      <div class='row'>
        <div class='cell'>left</div>
        <div class='cell center'>center</div>
        <div class='cell'>right</div>
      </div>
    </div>