3

I wondering if there is an easy way to do this via HTML / CSS.

I have a dynamic fixed-width table with 4 columns:

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

What I want is always have all the columns with data have all the same width.

So if any column is completely empty, I want it to collapse and the remaining columns would all have the same width.

I know that my jsFiddle is not correct, but I wanted to have one as a starting point.

I did review How to get table cells evenly spaced?, but is not exactly what I am looking for. I also reviewed Evenly spaced fixed-width columns - in a responsive setting, but that one also not the same.

EDIT:

td:empty {display: none} is a not the solution because if another row has has text in that column, the table gets distorted. jsFiddle

Community
  • 1
  • 1
malkassem
  • 1,937
  • 1
  • 20
  • 39

3 Answers3

8

UPDATE

in case of more than one row :

Solution is as describe below, to have it work, you need <tr> to be displayed as a single table : http://jsfiddle.net/zTbGB/7/ http://jsfiddle.net/zTbGB/8/

tr {
    display:table;
     table-layout: fixed;
    width:100%;
}

=================================================

you can set : table-layout:fixed on table element. http://jsfiddle.net/zTbGB/1/

See: http://www.w3.org/TR/CSS21/tables.html#fixed-table-layout

Then you can use the :empty selector :

td:empty {display:none;}

http://jsfiddle.net/zTbGB/3/

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
3

You can try this Fiddle. Seems to work well. In the CSS below, I'm using the ::empty pseudo selector. That selector won't work in IE8 or less, so if you're supporting IE8, then you'll need to augment this code with some javascript to hide those empty <td>'s.

CSS

table
{
    width: 400px;
    table-layout: fixed;
}
td:empty { display: none; }
dlane
  • 1,131
  • 7
  • 7
  • I updated the question. This does not work correctly. – malkassem Feb 13 '14 at 15:39
  • I recommend you [check out this thread](http://stackoverflow.com/questions/16764404/calculate-and-set-colspan-value-dynamically). With some tweaking, it should be able to help you. There is no way in CSS to be able to dynamically assign `colspan` values to your HTML. – dlane Feb 13 '14 at 15:49
  • 1
    You have a work around by breaking the table into many ones displaying as single tables : http://jsfiddle.net/zTbGB/8/ – G-Cyrillus Feb 13 '14 at 16:04
1

I have tried code for you using jQuery :) , you can use following code using jQuery:

$("#parent td").each(function() {


     if ($(this).text() == ''){
         var val=$(this).val();
        //alert(len);
     $(this).remove();


     }

});
var len=$("#parent td").length;
         var wit=100/len;
     //wit=wit+"%";
$("table td").width(wit + "%");

updated here http://jsfiddle.net/zTbGB/6/