Table class for tables that, when too wide split all their cells into rows

As I have already stated in the comments, what the OP is looking for cannot be achieved without the use of Javascript, so here is what I came up with.

Initially we have a normal table structure, we calculate each table’s width and apply a data-width attribute on each table – parent or nested.

On resize, as soon as each table is longer than the window width, it changes its contents display from table-cell to block, thus stacking all children.

As soon as the window width is expanded it is compared to each table’s data-width attribute and when it fits, it expands.

edit: I thought for some reason it wouldn’t work under some cases, but it actually works, so I remove the bloat!

HTML:

<div class="table">
  <div class="cell">
    Content 1
  </div>
  <div class="cell">
    <div class="table">
      <div class="cell">
        Content 1
      </div>
      <div class="cell">
        Cont
      </div>
      <div class="cell">
        Content 3
      </div>    
    </div>
  </div>
  <div class="cell">
    Content 3Content 3Content 3
  </div>

</div>

CSS:

.table {
  display: table;
  border: 1px solid #e4e5e7;
  white-space: nowrap;
}

.cell {
  display: table-cell;
  vertical-align: middle;
  padding: 10px;
  border: 1px solid #e4e5e7;
}

.cell .table {
  margin-bottom: -2px;
}

.table.wrap {
  white-space: normal;
}

.table.wrap > .cell {
  display: block;
}

Javascript:

$('.table').each(function(i) {
  tw = 0;
  $(this).children('.cell').each(function() {
    tw += $(this).outerWidth(true);
  });
  $(this).attr('data-width', tw);
});

$(window).on('load resize', function() {
  w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  $('.table').each(function(i) {
    if ($(this).width() >= w) {
      $(this).addClass('wrap');
    } else if (w >= $(this).attr('data-width')) {
      $(this).removeClass('wrap');    
    }
  });
}).resize();

And here is a working fiddle

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)