Styling tables using CSS - javascript

I have a problem with styling tables using CSS.
So I have a table in my HTML file:
<table class="altrowstable" id="alternatecolor">
<tr>
<th>Info Header 1</th><th>Info Header 2</th><th>Info Header 3</th>
</tr>
<tr>
<td>Text 1A</td><td>Text 1B</td><td>Text 1C</td>
</tr>
<tr>
<td>Text 2A</td><td>Text 2B</td><td>Text 2C</td>
</tr>
<tr>
<td>Text 3A</td><td>Text 3B</td><td>Text 3C</td>
</tr>
<tr>
<td>Text 4A</td><td>Text 4B</td><td>Text 4C</td>
</tr>
<tr>
<td>Text 5A</td><td>Text 5B</td><td>Text 5C</td>
</tr>
</table>
Here is my JavaScript file:
function altRows(id){
if(document.getElementsByTagName){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
if(i % 2 == 0){
rows[i].className = "evenrowcolor";
}else{
rows[i].className = "oddrowcolor";
}
}
}
}
window.onload=function(){
altRows('alternatecolor');
}
And here is my CSS file:
table.altrowstable {
font-family: verdana,arial,sans-serif;
font-size:11px;
color:#333333;
border-width: 1px;
border-color: #a9c6c9;
border-collapse: collapse;
}
table.altrowstable th {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #a9c6c9;
}
table.altrowstable td {
border-width: 1px;
padding: 8px;
border-style: solid;
border-color: #a9c6c9;
}
table.oddrowcolor{
background-color:#d4e3e5;
}
table.evenrowcolor{
background-color:#c3dde0;
}
The problem is that it is not changing color neither odd rows nor even odd.
What am I doing wrong?
Thanks.

I'll provide you a CSS solution for this:
table.class_name tr:nth-child(odd) {
/* Styles */
}
table.class_name tr:nth-child(even) {
/* Styles */
}
That's all you need, although it’s not supported in IE 8 and earlier.
Demo
For your table headers, you can simply use a different selector to over ride the background styles like
table.altrowstable tr th {
background: #fff;
}
Demo 2

I did check your code and found a little correction iin the css is needed to get the expected solution. There should be an empty space between the table and row classname.
table .oddrowcolor{
background-color:#d4e3e5;
}
table .evenrowcolor{
background-color:#c3dde0;
}

I like to provide solutions that dont tinker or modify the original source much.
Your HTML is fine, JScript is fine(very fine). Good to see that you use the .classname so that is is cross brwoser compatible.So all i did is change the classes for the CSS
YOUR CODE
table.oddrowcolor {
background-color:#d4e3e5;
}
table.evenrowcolor {
background-color:#c3dde0;
}
MY CHANGE
tr.oddrowcolor {
background-color:#d4e3e5;
}
tr.evenrowcolor {
background-color:#c3dde0;
}
WORKING FIDDLE
total change from your code to mine. 8 characters. Simple ain't it?

You have a problem within your CSS. You are setting the class for table, while as it should be for td.
You also need to modify your below js as style can be applied to td and not to tr
var rows = table.getElementsByTagName("td");
Here is the problem in your CSS
table.oddrowcolor{
background-color:#d4e3e5;
}
table.evenrowcolor{
background-color:#c3dde0;
}
You should be using this instead
table td.oddrowcolor{
background-color:#d4e3e5;
}
table td.evenrowcolor{
background-color:#c3dde0;
}
jsFiddle

Try this one ...see the Demo
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

Related

When using border-collapse, how to compute border-bottom-width in JavaScript?

When using table { border-collapse: collapse; } combined with th { border-bottom: 11px solid black }, it seems impossible to compute the border-bottom-width in JavaScript.
window.getComputedStyle(th).getPropertyValue('border-bottom-width') does not help at all. Just see what this fiddle logs to the console in different browsers...
Chrome: 11px
IE11: 5.5px
Firefox: 6px
If I remove border-collapse all browsers return 11px, as I would expect.
Is there a more reliable way to get the precise border-width when using border-collapse? OR is there a way to get the height (including borders) of either the thead, tr or th without running into the same inconsistencies between browsers?
Interesting! Seems like it's a plain inconsistency between browsers, don't think there's a simple solution to this. Anyways, here's a hacky solution/workaround:
var th = document.getElementById('th');
var table = document.getElementById('table');
var style = window.getComputedStyle(th);
table.style.borderCollapse = 'separate';
var borderHeight = style.getPropertyValue('border-bottom-width');
table.style.borderCollapse = 'collapse';
console.log(borderHeight);
table {
border-collapse: collapse;
}
th {
border-bottom: 11px solid red;
}
<table id="table">
<tr>
<th id="th">TH</th>
</tr>
</table>
Tested in Chrome & Firefox, both returned 11px.
EDIT: Based on #Eric N's answer, you might get lucky adding display: block to the ths. That would break the table layout then and you would need to work around that. Example for that:
var th = document.getElementById('th');
var style = window.getComputedStyle(th);
var borderHeight = style.getPropertyValue('border-bottom-width');
console.log(borderHeight);
table {
border-collapse: collapse;
}
th {
display: block;
float: left;
border-bottom: 11px solid red;
}
<table id="table">
<tr>
<th id="th">TH</th>
<th>TH</th>
<th>TH</th>
</tr>
</table>
Based on this post, it appears having a display:table-cell (inherit for your cells) yield different height/border-width results in different browsers. They suggest changing the display to block on your th to force the browser to calculate that value as you would expect.

Overriding a style sheet with jquery's addClass method

NOTE: adding $.tablesorter.defaults.widgets = ['zebra']; fixed the issue.
I have a simple table of records that was styled to alternate row colors:
inv_style.css
.tr_evn {background-color:#FFFFFF;}
.tr_odd {background-color:#F8F8F8;}
home.html
$(document).ready(function(){
$("#tbl_inv > tbody > tr:odd").addClass("tr_odd");
$("#tbl_inv > tbody > tr:even").addClass("tr_evn");
});
<table id="tbl_inv">...</table>
The table was then made sortable using tablesorter
$(document).ready(function(){
$("#tbl_inv").tablesorter();
$("#tbl_inv > tbody > tr:odd").addClass("tr_odd");
$("#tbl_inv > tbody > tr:even").addClass("tr_evn");
});
<table id="tbl_inv" class="tablesorter">...</table>
Up to this point I was still getting alternate row coloring that sorting would mess up and which I was about to fix. I first needed to add a custom stylesheet for the tablesorter table (for uniformity):
style_tablesorter.css
table.tablesorter{
font-family: Arial, sans-serif;
background-color: #BBBBBB;
margin:10px 0pt 15px;
font-size: 10px;
text-align: left;
padding:0px;
}
...
This style overrides the previous color alternation. All's I want to know is where to place the jquery addClass call's above so that they override this stylesheet?
Solution Attempts
I tried moving the addClass calls to
$(document).load()
$(window).ready()
$(window).load()
which had no effect.
I then tried manipulating document.styleSheets (Changing CSS Values with Javascript) which did work to simply change all the background-color's to the same color
var ss = document.styleSheets[x]; //x: index of style_tablesorter.css
var rules = ss[document.all ? 'rules' : 'cssRules'];
for(var i=0; i<rules.length; i++) {
rules[i].style.setProperty("background-color","white");
}
I then tried, for the hell of it, using a the jquery style selector from my calls above ("#tbl_inv > tbody > tr:odd")
for(var i=0; i<rules.length; i++) {
rules[i].addRule("#tbl_inv > tbody > tr:odd", "background-color: white");
}
Why are you not using even and odd to style the rows that way when the table is sorted it does not mess up the colors?
tbody tr:nth-child(even) td{
background-color: #aaa;
}
tbody tr:nth-child(odd) td{
background-color: #cfc;
}
table { border-collapse: collapse}
<table>
<tbody>
<tr><td>1</td><td>1</td></tr>
<tr><td>2</td><td>2</td></tr>
<tr><td>3</td><td>3</td></tr>
<tr><td>4</td><td>4</td></tr>
<tr><td>5</td><td>5</td></tr>
</tbody>
</table>
You could un-complicate the whole thing using pseudo-classes.
tr:nth-child(even) { background: #fff; }
tr:nth-child(odd) { background: #f8f8f8; }

Why doesn't `tbody` set the background color in a table?

I am using <tbody> as a CSS selector to set the background-color in a table. I'm doing this because I have multiple <tbody> sections within the table, and they have different background colors.
My issue is that when using border-radius on the cells, the cell doesn't respect the background-color of the tbody. That is, the border radius cuts out the corners in the default background color (in this case white), not the tbody color (in this case, green), below.
UPDATE: This problem occurs in Chrome/Safari, but not in Firefox (just tested myself on all 3). Still looking for a workaround on Chrome (FOUND! See accepted answer).
tr:first-child td:first-child {
background-color: red;
border-radius: 25px;
}
table {
border-spacing: 0px;
}
table tbody {
background-color: green;
}
<table>
<tbody>
<tr>
<td><p>TOP LEFT</p></td>
<td><p>TOP RIGHT</p></td>
</tr>
<tr>
<td><p>BOT LEFT</p></td>
<td><p>BOT RIGHT</p></td>
</tr>
</tbody>
</table>
To be clear, the fix I'm looking for would change the resultant example so it looks like this (I'm just changing the table tbody selector to table only):
tr:first-child td:first-child {
background-color: red;
border-radius: 25px;
}
table {
border-spacing: 0px;
}
table { /* changed this line */
background-color: green;
}
<table>
<tbody>
<tr>
<td><p>TOP LEFT</p></td>
<td><p>TOP RIGHT</p></td>
</tr>
<tr>
<td><p>BOT LEFT</p></td>
<td><p>BOT RIGHT</p></td>
</tr>
</tbody>
</table>
I don't want to do it that way, because I want the background-color to be on the tbody (which I have multiple ones) NOT on the whole table.
Any way to make the tbody color show through?
Try making the <tbody> to render like a block element.
tbody {
background-color: green;
display: block;
}
tr:first-child td:first-child {
background-color: red;
border-radius: 25px;
}
table {
border-spacing: 0px;
}
tbody {
background-color: green;
display: block;
}
<table>
<tbody>
<tr>
<td><p>TOP LEFT</p></td>
<td><p>TOP RIGHT</p></td>
</tr>
<tr>
<td><p>BOT LEFT</p></td>
<td><p>BOT RIGHT</p></td>
</tr>
</tbody>
</table>
An updated answer for other users, if it helps.
On Chrome, the display: block fixes the issue. However, it causes other layout issues with the table, where it does not seem to respect widths. Using display: table instead seems to resolve both issues:
tbody {
background-color: green;
display: table;
}
Set cellspacing to 0, borders on the table to none, and collapse the table borders (to make sure there is not space around the colored boxes). Then apply the background color to the TD elements instead of the tbody element.

HTML Table with vertical rows

How do I make vertical tables in HTML? By vertical, I mean the rows will be vertical with table headers on the left.
I also need it the way so I can access these rows (in this case vertical) as in a normal table, with <tr>. This is because I get the data dynamically for one row (like for row A) and insert it in the table. I am using angularJS to avoid DOM manipulation, so I am not looking for complex DOM manipulation with Javascript.
If you want <tr> to display columns, not rows, try this simple CSS
tr { display: block; float: left; }
th, td { display: block; }
This should display what you want as far as you work with single-line cells (table behavior is dropped).
/* single-row column design */
tr { display: block; float: left; }
th, td { display: block; border: 1px solid black; }
/* border-collapse */
tr>*:not(:first-child) { border-top: 0; }
tr:not(:first-child)>* { border-left:0; }
<table>
<tr>
<th>name</th>
<th>number</th>
</tr>
<tr>
<td>James Bond</td>
<td>007</td>
</tr>
<tr>
<td>Lucipher</td>
<td>666</td>
</tr>
</table>
David Bushell has provided a solution and implementation here: http://dbushell.com/demos/tables/rt_05-01-12.html
The trick is to use display: inline-block; on the table rows and
white-space: nowrap; on the table body.
AFAIK, there is no magic solution to switch this around.
As for a rotation(90deg), that would most likely turn the whole table to the side, similar to how a sheet of paper would look if you turned in 90 degrees, and that's not what you want (I think?).
If this is possible (and realistic), I would suggest changing it in the HTML itself.
As indicated in the comments, there is no suggestion here, so here's a basic javascript alternative [even if this is not what you were looking for] using jQuery. Without knowing your experience, I've taken the time to comment everything to be sure you get what the code is doing.
// Change the selector to suit your needs
$('table').each(function(){
var table = $(this), // Reference each table in the page
header = $('thead', table), // Reference the table head
headings = []; // Set an array for each column
// If the table doesn't have a header, use it's footer for column titles
if(!header.length)
header = $('tfoot', table);
// If there's no header nor footer, skip to the next table
if(!header.length)
continue;
// Loop each heading to get the header value
$('th', header).each(function(){
var heading = $(this).html(); // Each heading value content, including any HTML; use .text() to use the text only
headings.push(heading); // Add heading value to array
});
// Make sure the content is wrapped in a tbody element for proper syntax
if(!$('tbody', table).length)
table.wrapInner('<tbody></tbody>');
// Set counter to reference the heading in the headings array
var x = 0;
// Loop through each row in the table
$('tbody tr').each(function(){
var row = $(this),
label = headings[x];
// Add the heading to the row, as a <th> for visual cues (default: bold)
row.prepend('<th>'+label+'</th>')
// Move to the next value in the headings value
x++;
});
});
You can use <th> as the first cell in the row.
Here's a fiddle: http://jsfiddle.net/w5nWG/
#vishesh so you want to transpose your table after DOM ready? try this http://gist.github.com/pgaertig/2376975
$(function() {
var t = $('#thetable tbody').eq(0);
var r = t.find('tr');
var cols= r.length;
var rows= r.eq(0).find('td').length;
var cell, next, tem, i = 0;
var tb= $('<tbody></tbody>');
while(i<rows){
cell= 0;
tem= $('<tr></tr>');
while(cell<cols){
next= r.eq(cell++).find('td').eq(0);
tem.append(next);
}
tb.append(tem);
++i;
}
$('#thetable').append(tb);
$('#thetable').show();
}
<table>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
table { border-collapse: collapse; }
table tr { display: block; float: left; }
table tr tr{ display: block; float: left; }
table th, table td { display: block; border: none; }
try this
<table>
<thead>
<tr>
<th>id</th>
<th>column1</th>
<th>column2</th>
<th>column3</th>
<th>column4</th>
<th>column5</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
css:
table, td, th {
border: 1px solid red;
}
thead {
float: left;
}
thead th {
display: block;
background: yellow;
}
tbody {
float: right;
}
Maybe this link won't help : rotate a table 90 degrees
neither would this one : http://www.w3.org/TR/html401/struct/tables.html
Otherwise, you can try this, has another user suggested (rejected and downvoted) :
table {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
This sounds silly, but hey, it's not worse than just not knowing the 'verry basic' HTML 4 table model.

html: hover table column [duplicate]

This question already has answers here:
Cols, colgroups and css ":hover" pseudoclass
(5 answers)
Closed 7 years ago.
How can I change the background column of an html table column when the mouse is over it?
Preferably with css only.
This can be done using CSS with no Javascript.
I used the ::after pseudo-element to do the highlighting. z-index keeps the highlighting below the <tds> in case you need to handle click events. Using a massive height allows it to cover the whole column. overflow: hidden on the <table> hides the highlight overflow.
Demo: http://jsfiddle.net/ThinkingStiff/2XeYe/
Output:
CSS:
table {
border-spacing: 0;
border-collapse: collapse;
overflow: hidden;
z-index: 1;
}
td, th {
cursor: pointer;
padding: 10px;
position: relative;
}
td:hover::after {
background-color: #ffa;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
HTML:
<table>
<tr>
<th></th><th>50kg</th><th>55kg</th><th>60kg</th><th>65kg</th><th>70kg</th>
</tr>
<tr>
<th>160cm</th><td>20</td><td>21</td><td>23</td><td>25</td><td>27</td>
</tr>
<tr>
<th>165cm</th><td>18</td><td>20</td><td>22</td><td>24</td><td>26</td>
</tr>
<tr>
<th>170cm</th><td>17</td><td>19</td><td>21</td><td>23</td><td>25</td>
</tr>
<tr>
<th>175cm</th><td>16</td><td>18</td><td>20</td><td>22</td><td>24</td>
</tr>
</table>
I have a more simple solution (Live example: http://jsfiddle.net/q3HHt/1/)
HTML:
<table>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
CSS:
table, td {
border: 1px solid black;
}
td {
width: 40px;
height: 40px;
}
.highlighted {
background-color: #348A75;
}
jQuery:
$('td').hover(function() {
var t = parseInt($(this).index()) + 1;
$('td:nth-child(' + t + ')').addClass('highlighted');
},
function() {
var t = parseInt($(this).index()) + 1;
$('td:nth-child(' + t + ')').removeClass('highlighted');
});
Live example: http://jsfiddle.net/q3HHt/1/
Only works for cells or rows, sorry.
e.g.
td {
background-color: blue;
}
td:hover {
background-color: red;
}
There are JavaScript solutions available but nothing in CSS right now will do what you want because of the limitations of selectors.
td /* all cells */
{
background-color: blue;
}
tr /* all rows */
{
background-color: pink;
}
/* nothing for all columns */
Just to extends Muhammads answer (https://stackoverflow.com/a/11828637/1316280), if you want to highlight the cols only in the actual table, change the jquery-code-part to:
this jsfiddle is specific for only the actual table
jQuery
$('td').hover(function() {
var t = parseInt($(this).index()) + 1;
$(this).parents('table').find('td:nth-child(' + t + ')').addClass('highlighted');
},
function() {
var t = parseInt($(this).index()) + 1;
$(this).parents('table').find('td:nth-child(' + t + ')').removeClass('highlighted');
});
jsFiddle: http://jsfiddle.net/q3HHt/123/
I do not think there is a clean HTML + CSS way to do this. Javascript is an alternative, for example the jQuery tableHover plugin
I had a similar problem where I had too many columns to display on screen. VIA PHP, I turned each row into a 1 x column table. So, n rows = n tables. I then nested each table within a master table. Doing so allowed me to call td:hover from my stylesheet. Since each td held a table, it has the same effect of highlighting the a column when I mouse over it.
You can try experimenting with <col> tag and col:hover { background: red; } style, but I doubt that it will work. Anyway, this definitely won't work in older versions of MSIE, so you will need javascript in order to do this.
You can highlight the whole row with pure CSS using:
tr td {background-color: red;}
tr:hover td {background-color: blue;}
Achieving this effect for a column is impossible with this approach, as cell (td) is a child of a row (tr), not a column.
To make it work in IE7+, make sure to add doctype declaration (what you should always do anyway:)).

Categories