Dynamic height for table cell in horizontal table - html

I used this answer to create a horizontal table as i have a fixed amount of horizontal rows but N number of vertical columns. This works really well but because the HTML rows are actually columns, the height between cells does not stay consistent in the displayed rows.
By adding the following to the answer provided, I'm able to ensure each column fits on the page, causing text wrap to occur, but then the rows height don't necessarily match.
td {
max-width: 200px;
}
JSFiddle example.
In the fiddle example above, how do I make the cell with "Title" and the cell with "Braveheart" match the height of the third cell in that row?
Hint: the correct answer is not to hard code the height of the first two cells, since I have no idea how long another cell may be when it is added later.
EDIT
I can't use JavaScript as the html never hits anything client side. It's rendered and then passed into a PDF creation utility.

This may not be the best performing answer, or even the most concise, but it could start you in the right path (fiddle):
<div>
<table>
<tbody>
<tr>
<th class="title">Title</th>
<th class="year">Release Year</th>
<th class="director">Director</th>
</tr>
<tr>
<td class="title">Braveheart</br>part 2</td>
<td class="year">1992?</td>
<td class="director">Mel Gibson?</td>
<tr>
<td class="title">Some movie with a ridiculously long title. I mean, like two paragraphs for a title, which is ridiculous of course but it proves my point.</td>
<td class="year">2015</td>
<td class="director">The Great Anton - Director of the year 2012</td>
</tr>
</tbody>
</table>
</div>
$(document).ready(function(){
function getMaxHeight(e){
var maxHeight = Math.max.apply(null, $(e).map(function ()
{
return $(this).height();
}).get());
return maxHeight;
}
$('tr').each(function(){
$(this).find('.title').css("height", getMaxHeight('.title'));
$(this).find('.year').css("height", getMaxHeight('.year'));
$(this).find('.director').css("height", getMaxHeight('.director'));
});
});
The max height function came from this SO answer.

Related

Scrollable html table with fixed first row and first column, along with angular material controls within the cells of table

I want to achieve the below result without using jquery:
The table for which data should be scrollable for both axis.
The first column (table header) and first row of the table should be a fixed and with auto adjustable width for the column as per the data entered, similar to google spreadsheet
Above image shows what I have tried, the element containing the table has overflow-x: auto for the horizontal scroll and the element has style="display:block;height:400px;overflow-y:auto" for the vertical scroll for fixed table header. Also some elements contain mat-elements
Following is the html code for above image:
<div style="overflow-x:auto">
<table>
<thead>
<tr>
<th>#</th>
<th>Textbox_1</th>
<th>Textbox_1</th>
<th>Multichoice</th>
</tr>
</thead>
<tbody style="display:block;height:400px;overflow-y:auto">
<tr>
<td>1</td>
<td><div>John</div></td>
<td><div>Ron</div></td>
<td><div><mat-select><mat-option>One</mat-option>
<mat-option>Two</mat-option>
</mat-select>
</div>
</td>
</tr>
</tbody>
</table>
</div>
Expected Result:
Any help is greatly appreciated.
I think it is not possible with CSS only. You might need support of JavaScript/JQuery. Check out this light weight plugin. It will help you for sure.
https://github.com/nitsugario/jQuery-Freeze-Table-Column-and-Rows

Full-height tables inside table cells

I am stuck working on this project that has to be produced as HTML tables.
The page has an outer table with 2 rows: a header/branding cell and then a cell that holds a second table.
This table is dynamically generated by an app and might have any number of rows and columns. The app determines the number of rows and columns requested and spits out the html accordingly.
Every created cell holds another table as a "widget" with the title row and a content row, as shown below. The content row holds an SVG chart.
<table class="widget">
<tbody>
<tr id="trtitlewidget22">
<td id="titlewidget22" class="widget-header"><h3>Enquiries</h3></td>
</tr>
<tr>
<td class="widget-content" id="widget22">
[this would be a js svg chart]
</td>
</tr>
</tbody>
</table>
Here is a fiddle of the whole layout minus the charts (i used filler text). Here's a screen cap:
What I need to do is have the "widget table" always fill its enclosing table cell, as the page is resized and the table flexes. I have tried height 100% to no avail.
I couldn't figure a css-only solution. I would go for a javascript approach. Here's how you can do it easily with JQuery. If you want it vanilla, is possible either:
var fitHeight = function() {
$("table.widget").each(function() {
$(this).removeAttr("style");
});
//It has to be separate from the remove loop, so the height will be re-applied.
$("table.widget").each(function() {
$(this).height($(this).parent().height());
});
}
$(window).resize(fitHeight);
$(document).ready(fitHeight);
http://jsfiddle.net/5LeK6/5/

HTML colspan 0 alternative

I have a HTML table, and i would like to give the last row (in <tfoot> tag) only one cell expanding to all the table.
I was using colspan="0", then i saw that it only worked in Firefox.
I then tried colspan="100%".
It works fine, but not pass the w3c validator (Very important in my project).
Is there a working alternative ?
I saw people who use colspan="1000", not a bad idea but are there some performance problems with this ?
Thanks for advice.
My first answer is: refactor your code. If you need the total number of columns to build the table footer then the function you use to build the table body should return that number (and not only the HTML).
That said and only in case it's too complicated (or you don't have control about that code) you may simply count them by yourself, I would avoid any trick about colspan because it's behavior isn't homogeneous (and it's not validated too).
You can easy count the number of cells using the first row (if the table is well formed all the rows have the same number of columns).
The first naive solution would be to split() HTML tbody then to substr_count() the <td/> of the first row. Unfortunately this may work only in a very controlled situation (tables must be well formed, table may contain or not tbody and it doesn't manage colspan of that cells).
Better solution involves a small HTML parser (see this great post here on SO for a good and detailed list), when you have DOM then you can easily count TDs and check for their attributes (I say this in advance: no, you can't use regex to parse HTML).
To be honest I think refactoring is much more suitable...
Might be the following code I use could be useful too:
var len = document.getElementById("myTable").rows[0].cells.length;
document.getElementById("myTablelastrowfirstcell").colSpan = len;
the first line gets into the variable len the number of cells (td or th elements, doesn't matter, if all the table has the same number of column) contained into the first row of mytable;
The second row modifies the colspan property/attribute of the targeted cell positioned into the last row and sets it to the value previously got.
The following has the same code, shortened:
document.getElementById("myTablelastrowfirstcell").colSpan = document.getElementById("myTable").rows[0].cells.length;
Notes:
Sometimes the table contains a thead, a tbody and a tfoot. In such
case it is needed to modify the code using the id of one of them
that has the correct number of columns to return.
The given examples, in some situations, might work only when rendered by the browser, if rendered for printing they might won't work anymore and table layout might be different.
Working example (click on run code example at the end of the code to run it and see how it operates):
function spanLastRowCols() {
var len = document.getElementById("myTable").rows[0].cells.length;
var len = document.getElementById("ext").colSpan = len;
info.innerText = len;
}
table, td {
border: 1px solid black;
}
<p>Click the button to change the content of the first table cell.</p>
<p>Then copy and paste some td cells for each rows forthe first and the second tr. Than run the snippet again and click the button to change the content of the first table cell to compare differences.</p>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
<td>Row1 cell3</td>
<td>Row1 cell4</td>
<td>Row1 cell5</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
<td>Row2 cell3</td>
<td>Row2 cell4</td>
<td>Row2 cell5</td>
</tr>
<tr>
<td id= "ext">Row3 cell1</td>
</tr>
</table>
<br>
<button onclick="spanLastRowCols()">Try it</button>
Last row colSpan attribute value: <span id="info"></span>
The <caption> tag is well supported and will give you a result similar to <tfoot colspan="1000">:
table {
background: #eee;
}
table caption {
background: #e0e0e0;
}
td,
th {
margin: 5px;
padding: 5px;
}
<table>
<thead>
<th>Quote</th>
<th>Author</th>
<th>More</th>
<tbody>
<tr>
<td>One cow at a time, set free the entire herd</td>
<td colspan="2">Prosper Stupefy</td>
</tr>
</tbody>
<caption style="caption-side:bottom">This will always span to the full width of the table</caption>
<caption style="caption-side:top">A list of made-up quotes</caption>
</table>
Note that you will need to css style it.
Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption

Table rows become inline if rowspan is set for all the cells of the row

Here is what I need to do.
I'm creating a grid with widgets that are supposed to be represented in a table. Each widget has a variable width that represents the colspan of the td that contains it, and a height of 1 or 2 that is supposed to represent the rowspan of that cells.
Everything works fine, until I'm having a case where all the cells of a row have a colspan of 2, and the next row can have any type of cells. The next row is getting displayed right next to the previous row instead of the next one.
Here is a jsfiddle that replicates the problem and here is the code:
<table>
<tr>
<td rowspan = "2">ONE</td>
</tr>
<tr>
<td rowspan = "1">1</td>
<td rowspan = "1">2</td>
<td rowspan = "1">3</td>
<td rowspan = "1">4</td>
</tr>
</table>
Is this a bug? Am I doing something wrong?
EDIT: To be clear, what I want to do, is having a row of widgets that have twice the height of a regular row
It's difficult to visualize exactly what you want, but perhaps you should be using block elements rather than a table. A table should only be used for tabular data. The rowspan attribute won't function correctly if there aren't any rows to span.
<table>
<tr>
<td rowspan="2">ONE</td>
<td>TWO</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</table>
See the fiddle
Instead of forcing a thing to two rows, which is normally only done when you have more cells in that set of rows, simply set the cell's height:
http://jsfiddle.net/vjPMw/5/
td {
height: 20px;
background-color: #eee;
}
td.doubleheight {
height: 40px;
}
<table>
<tr>
<td class="doubleheight">ONE</td>
</tr>
<tr>
<td rowspan = "1">1</td>
<td rowspan = "1">2</td>
<td rowspan = "1">3</td>
<td rowspan = "1">4</td>
</tr>
</table>
Really, I'd have expected even that to be unnecessary, as a cell normally expands to contain its contents. Maybe a more complete demo of your situation is in order. Also, I agree with Aarolama Bluenk that maybe a table isn't the right approach here to begin with.
The first row has 1 cell with rowspan=2, so html expects next row to be the one which is "spanned", however you've added row with 4 td's.
I'd recommend adding empty <tr></tr> after first one and play with it OR fix first td to: <td rowspan="2" colspan="4">ONE</td>

Colspan all columns

How can I specify a td tag should span all columns (when the exact amount of columns in the table will be variable/difficult to determine when the HTML is being rendered)? w3schools mentions you can use colspan="0", but it doesn't say exactly what browsers support that value (IE 6 is in our list to support).
It appears that setting colspan to a value greater than the theoretical amount of columns you may have will work, but it will not work if you have table-layout set to fixed. Are there any disadvantages to using an automatic layout with a large number for colspan? Is there a more correct way of doing this?
Just use this:
colspan="100%"
It works on Firefox 3.6, IE 7 and Opera 11! (and I guess on others, I couldn't try)
Warning: as mentioned in the comments below this is actually the same as colspan="100". Hence, this solution will break for tables with css table-layout: fixed, or more than 100 columns.
I have IE 7.0, Firefox 3.0 and Chrome 1.0
The colspan="0" attribute in a TD is NOT spanning across all TDs in any of the above browsers.
Maybe not recommended as proper markup practice, but if you give a higher colspan value than the total possible no. of columns in other rows, then the TD would span all the columns.
This does NOT work when the table-layout CSS property is set to fixed.
Once again, this is not the perfect solution but seems to work in the above mentioned 3 browser versions when the table-layout CSS property is automatic.
If you want to make a 'title' cell that spans all columns, as header for your table, you may want to use the caption tag (http://www.w3schools.com/tags/tag_caption.asp / https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) This element is meant for this purpose. It behaves like a div, but doesn't span the entire width of the parent of the table (like a div would do in the same position (don't try this at home!)), instead, it spans the width of the table. There are some cross-browser issues with borders and such (was acceptable for me). Anyways, you can make it look as a cell that spans all columns. Within, you can make rows by adding div-elements. I'm not sure if you can insert it in between tr-elements, but that would be a hack I guess (so not recommended). Another option would be messing around with floating divs, but that is yuck!
Do
<table>
<caption style="gimme some style!"><!-- Title of table --></caption>
<thead><!-- ... --></thead>
<tbody><!-- ... --></tbody>
</table>
Don't
<div>
<div style="float: left;/* extra styling /*"><!-- Title of table --></div>
<table>
<thead><!-- ... --></thead>
<tbody><!-- ... --></tbody>
</table>
<div style="clear: both"></div>
</div>
As a partial answer, here's a few points about colspan="0", which was mentioned in the question.
tl;dr version:
colspan="0" doesn't work in any browser whatsoever. W3Schools is wrong (as usual). HTML 4 said that colspan="0" should cause a column to span the whole table, but nobody implemented this and it was removed from the spec after HTML 4.
Some more detail and evidence:
All major browsers treat it as equivalent to colspan="1".
Here's a demo showing this; try it on any browser you like.
td {
border: 1px solid black;
}
<table>
<tr>
<td>ay</td>
<td>bee</td>
<td>see</td>
</tr>
<tr>
<td colspan="0">colspan="0"</td>
</tr>
<tr>
<td colspan="1">colspan="1"</td>
</tr>
<tr>
<td colspan="3">colspan="3"</td>
</tr>
<tr>
<td colspan="1000">colspan="1000"</td>
</tr>
</table>
The HTML 4 spec (now old and outdated, but current back when this question was asked) did indeed say that colspan="0" should be treated as spanning all columns:
The value zero ("0") means that the cell spans all columns from the current column to the last column of the column group (COLGROUP) in which the cell is defined.
However, most browsers never implemented this.
HTML 5.0 (made a candidate recommendation back in 2012), the WhatWG HTML living standard (the dominant standard today), and the latest W3 HTML 5 spec all do not contain the wording quoted from HTML 4 above, and unanimously agree that a colspan of 0 is not allowed, with this wording which appears in all three specs:
The td and th elements may have a colspan content attribute specified, whose value must be a valid non-negative integer greater than zero ...
Sources:
https://www.w3.org/TR/html50/tabular-data.html#attributes-common-to-td-and-th-elements
https://html.spec.whatwg.org/multipage/tables.html#attributes-common-to-td-and-th-elements
https://www.w3.org/TR/html53/tabular-data.html#attributes-common-to-td-and-th-elements
The following claims from the W3Schools page linked to in the question are - at least nowadays - completely false:
Only Firefox supports colspan="0", which has a special meaning ... [It] tells the browser to span the cell to the last column of the column group (colgroup)
and
Differences Between HTML 4.01 and HTML5
NONE.
If you're not already aware that W3Schools is generally held in contempt by web developers for its frequent inaccuracies, consider this a lesson in why.
For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".
The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:
IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.
The bug is well documented.
If you're using jQuery (or don't mind adding it), this will get the job done better than any of these hacks.
function getMaxColCount($table) {
var maxCol = 0;
$table.find('tr').each(function(i,o) {
var colCount = 0;
$(o).find('td:not(.maxcols),th:not(.maxcols)').each(function(i,oo) {
var cc = Number($(oo).attr('colspan'));
if (cc) {
colCount += cc;
} else {
colCount += 1;
}
});
if(colCount > maxCol) {
maxCol = colCount;
}
});
return maxCol;
}
To ease the implementation, I decorate any td/th I need adjusted with a class such as "maxCol" then I can do the following:
$('td.maxcols, th.maxcols').each(function(i,o) {
$t = $($(o).parents('table')[0]); $(o).attr('colspan', getMaxColCount($t));
});
If you find an implementation this won't work for, don't slam the answer, explain in comments and I'll update if it can be covered.
Another working but ugly solution : colspan="100", where 100 is a value larger than total columns you need to colspan.
According to the W3C, the colspan="0" option is valid only with COLGROUP tag.
Below is a concise es6 solution (similar to Rainbabba's answer but without the jQuery).
Array.from(document.querySelectorAll('[data-colspan-max]')).forEach(td => {
let table = td;
while (table && table.nodeName !== 'TABLE') table = table.parentNode;
td.colSpan = Array.from(table.querySelector('tr').children).reduce((acc, child) => acc + child.colSpan, 0);
});
html {
font-family: Verdana;
}
tr > * {
padding: 1rem;
box-shadow: 0 0 8px gray inset;
}
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
<th>Header 5</th>
<th>Header 6</th>
</tr>
</thead>
<tbod><tr>
<td data-colspan-max>td will be set to full width</td>
</tr></tbod>
</table>
Simply set colspan to the number of columns in the table.
All other "shortcuts" have pitfalls.
The best thing to do is set the colspan to the correct number to begin with. If your table has 5 columns, set it to colspan="5" That is the only way that will work in all scenarios. No, it's not an outdated solution or only recommended for IE6 or anything -- that's literally the best way to handle this.
I wouldn't recommend using Javascript to solve this unless the number of columns changes during runtime.
If the number of columns is variable, then you'll need to calculate the number of columns so that you can populate the colspan. If you have a variable number of columns, whatever is generating the table should be able to be adapted to also calculate the number of columns the table has.
As other answers have mentioned, if your table is not set to table-layout: fixed, you can also just set colspan to a really large number. But I find this solution messy, and it can be a headache if you come back later and decide it should be a fixed table layout. Better just to do it correctly the first time.
A CSS solution would be ideal, but I was unable to find one, so here is a JavaScript solution: for a tr element with a given class, maximize it by selecting a full row, counting its td elements and their colSpan attributes, and just setting the widened row with el.colSpan = newcolspan;. Like so...
var headertablerows = document.getElementsByClassName('max-col-span');
[].forEach.call(headertablerows, function (headertablerow) {
var colspan = 0;
[].forEach.call(headertablerow.nextElementSibling.children, function (child) {
colspan += child.colSpan ? parseInt(child.colSpan, 10) : 1;
});
headertablerow.children[0].colSpan = colspan;
});
html {
font-family: Verdana;
}
tr > * {
padding: 1rem;
box-shadow: 0 0 8px gray inset;
}
<table>
<tr class="max-col-span">
<td>1 - max width
</td>
</tr>
<tr>
<td>2 - no colspan
</td>
<td colspan="2">3 - colspan is 2
</td>
</tr>
</table>
You may need to adjust this if you're using table headers, but this should give a proof-of-concept approach that uses 100% pure JavaScript.
Anyone else here feel that diving into JS for this seemingly minor issue seems a bit much?
PURE CSS
Boom! I have a pure CSS solution to offer you! Example is below, you just have to add a class to the row that you want to span all columns. Then the CSS will make the first <td> element span the full width and hide the remaining <td> elements. (You must use visibility:hidden; and NOT display:none; for this.)
Note: You will need at least two cells for this method to render nicely, and CSS will render best if you keep the correct quantity of <td> elements - don't remove any to make room for span element. This will help ensure the cells / rows still flow normally.
EXAMPLE
/* standard styling css */
table {
border-collapse: collapse;
}
table, tr, td {
border: 1px solid black;
}
td {
padding: 3px;
}
/* make full width class span the whole table */
.full-span {
position:relative;
}
.full-span > * {
visibility: hidden;
border:0;
}
.full-span > *:nth-child(1) {
display: block;
visibility: unset;
position:absolute;
}
<table>
<tbody>
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
<td>A4</td>
</tr>
<tr class="full-span">
<td>B1 long text</td>
<td>B2</td>
<td>B3</td>
<td>B4</td>
</tr>
<tr>
<td>C1</td>
<td>C2</td>
<td>C3</td>
<td>C4</td>
</tr>
<tr>
<td>D1</td>
<td>D2</td>
<td>D3</td>
<td>D4</td>
</tr>
</tbody>
</table>
Bonus tip!
if you are dynamically producing your table in PHP/JS, this may clean up some of your code. Say you are looping through a 2D array to create a table: for each row that needs to span all columns you'll need to add some logic to calculate the amount of columns, add the colspan attribute, add any remaining <td> elements required to make up the full width of the table and so on.
Using my method, you can loop through all the columns and output them all, and simply include the class in the parent row.
Just want to add my experience and answer to this.
Note: It only works when you have a pre-defined table and a tr with ths, but are loading in your rows (for example via AJAX) dynamically.
In this case you can count the number of th's there are in your first header row, and use that to span the whole column.
This can be needed when you want to relay a message when no results have been found.
Something like this in jQuery, where table is your input table:
var trs = $(table).find("tr");
var numberColumns = 999;
if (trs.length === 1) {
//Assume having one row means that there is a header
var headerColumns = $(trs).find("th").length;
if (headerColumns > 0) {
numberColumns = headerColumns;
}
}
colspan="100%"
it's work also in email outlook , gmail....