How to remove padding and border from table cells? - html

I tried a lot of solutions that I have found here and in Google, but no one of them works.
The table is dynamically generated by jQuery and Javascript.
Question:
How can I remove the padding, border between the cells in this html table ?
This is the HTML code:-
<div class="board">
<table id="tableGame">
</table>
</div>
This is the Css Code
.board{
float:left;
display: inline-block;
}
table{
border-collapse: collapse;
}
table tr, td{
border: 0px;
}
Javascript Code below
function mapGenerate(){
var map=createMap(); // this function returns a 2d array filled of random 1 and 0
/* example
map = [[1,1,1,1,0],
[1,0,0,0,0],
[1,0,1,1,1],
[1,0,0,0,1],
[1,1,1,0,1]]
*/
//loop the 2d array map and change the number with the appropriate img
for(var i = 0; i < map.length; i++) {
var innerArrayLength = map[i].length;
for(var j = 0; j<innerArrayLength; j++){
//loop the nested arrays so i can change the 1 and the 0 with the appropriate img
if(map[i][j] === 0){
map[i][j]="<img class=\"walkble\" src=\"mapTiles/floorResized.png\">"; //you can walk this part of the map
}else{
map[i][j]="<img class=\"nonWalkble\"// you cannot walk This part of the map src=\"mapTiles/volcanoresize.png\">";
}
;
}
$("#tableGame").append("<tr><td>"+ map[i] + "</td></tr>") // Here i print the elements of the array
}
}
mapGenerate();
Link to jsfiddle under here.
The problem is not about the 3rd white line ( it only appears in js fiddle, if I open it in my browser they looking as a normal table).
The problem is only to delete that disturbing padding between the cells.
jsfiddle
In codepen you will see it better, without lines error.
codepen

looks like the problem is on line 80 of your javascript.
$("#tableGame").append("<tr><td>"+ map[i] + "<td></tr>")
you're concat-ing an array (map[i]) into a string. javascript by default "stringify" it by joining it with commas.
The code above is like:
$("#tableGame").append("<tr><td>"+ map[i].join() + "<td></tr>")
since the default joining string is comma, that's equivalent to
$("#tableGame").append("<tr><td>"+ map[i].join(',') + "<td></tr>")
To get rid of the commas you simply joining it with an empty string
$("#tableGame").append("<tr><td>"+ map[i].join('') + "<td></tr>")

In HTML, there are attributes border, cellpadding, and cellspacing on the <table> element. Set them to 0. <table border="0" cellpadding="0" cellspacing="0">.
Border is for the border width.
Cellpadding is for the padding in the table cells.
Cellspacing is for the space between the table cells.

css:
table { border-collapse: collapse; }
table td { padding:0; }

Related

How to freeze header and left columns of the table

I want to fix header and 3 left columns of my table.
But I found only one suitable solution. Here is link: http://hazaa.com.au/blog/how-to-create-an-html-table-with-frozen-headers-and-columns/
I need to divide my table to 4 independent tables and that's not good.
Also I found plugin http://www.fixedheadertable.com/ (as suggestion in another such question on SO) unfortunately it can freeze only one left column (I need 3 columns).
Are there any other simple ways to implement this feature?
the standard html table does not support frozen columns, even with css.
if you can use a jquery plugin, i suggest you to use http://www.datatables.net/ with the fixedcolumns plugin (just configure and it works as supposed :) )
if not, you will end up with u solution where you havo to split up the table in the one or the other way, and if you want to have scrollable tables you will have to use javascript since css and html do not support such features yet.
Thought I'd share how I've done this. This code is surely somewhat based off other code found on this site but have long since lost exactly where. Requires jQuery. Potentially doesn't support various odd things you might want to do to a table.
<div class='tableFreeze'>
<table>
<thead>
<tr><th>Headers</th><th>Go</th><th>Here</th></tr>
</thead>
<tbody>
<!--table body stuff goes here-->
</tbody>
</table>
</div>
<style>
.tableFreeze {
width: 800px;
max-height: 500px;
position: relative;
overflow: scroll;
}
</style>
<script>
$(document).ready(function(){
//Sets a table to have frozen headers, or both headers and first column
//A div around the table must have a class of 'tableFreeze'
//can also add class 'tableFreeze_headersOnly' to the div to specify only headers should be frozen
//Table inside of div must have one thead and one tbody
//can set the div to have custom CSS defining the width and max height
$('.tableFreeze').each(function(){
var div=$(this);
//get the table in the DIV
var table=div.children('table');
// save original width to table object
var table_original_width=table.width();
//do the same for each td or th in the header
table.find('thead tr td,thead tr th').each(function(){
$(this).attr("data-item-original-width",$(this).width());
});
//do the same for the heights of each first cell on the left
var table_original_height=table.height();
table.find('tr').each(function(){
$(this).find('td,th').eq(0).attr("data-item-original-height",$(this).find('td,th').eq(0).height());
});
//need a copy of the table to strip away and make it just the header
var table_header=table.clone();
//set the whole copy of this table to have the proper width
table_header.width(table_original_width);
//set width of all cells in the header
table_header.find('thead tr td,thead tr th').each(function(){
$(this).width($(this).attr("data-item-original-width"));
});
//remove the tbody
table_header.find('tbody').remove();
//set the width and height of this header bar. add a header class
table_header.css({'width':table_original_width,'height':table_header.find("td,th").first().attr('data-item-original-height'),"position":"absolute","left":0,"top":0}).addClass('tableFreeze_header');
//add to div
div.append(table_header);
//if we have this class, we don't need to do the rest
if ($(this).hasClass('tableFreeze_headersOnly')) return;
//another copy of the table for just the left bar
var table_leftcol=table.clone();
//go through each row (in both tbody and thead)
table_leftcol.find('tr').each(function(){
//remove all but the first cell
$(this).children('td,th').slice(1).remove();
//set the height of each cell to be the original height
$(this).children('td,th').height(($(this).children('td,th').attr("data-item-original-height")*1)+1);
});
//set: the height of the whole table based on the original height we got, the width based on the width set of the first cell, absolutely position it on the left and right, and an id for finding later
table_leftcol.css({'height':table_original_height,'width':table_leftcol.find("td,th").first().attr('data-item-original-width'),"position":"absolute","left":0,"top":0}).addClass('tableFreeze_leftcol');
//add to div
div.append(table_leftcol);
//and finally a similar thing for just the top left cell (a1). That will need to always be on the top left.
var table_a1=table.clone();
//set copy to be original table width
table_a1.width(table_original_width);
//get the width and height of the a1 cell
var table_a1_width=table_a1.find("thead tr td,thead tr th").eq(0).attr("data-item-original-width");
var table_a1_height=table_a1.find("thead tr td,thead tr th").eq(0).attr("data-item-original-height");
//remove all but the first cell in the header
table_a1.find("thead tr td,thead tr th").slice(1).remove();
//and remove the entire tbody
table_a1.find('tbody').remove();
//set the first (and should be only remaining) cell to have the proper width/height
table_a1.find("thead tr td,thead tr th").eq(0).width(table_a1_width).height(table_a1_height);
//table positionin' stuff
table_a1.css({'width':table_a1_width,'height':table_a1_height,"position":"absolute","left":0,"top":0}).addClass('tableFreeze_a1');
//add to div
div.append(table_a1);
});
});
</script>

Tricky styling creating blank space

Hello there, I just created this datepicker thingy which turned out pretty cool except that it creates some really annoying and weird looking white space below the divs when empty and appears higher, see the fiddle > http://jsfiddle.net/VtKkM/2/ Any help is greatly appreciated!
Haven't figured out the problem as of yet, but it seems that it doesn't like it when the spans are empty. One workaround, at least for now, is to replace your blank options with just a space ( ) so that there's still the illusion that it's empty but the spans still technically contain a value. This may not be a permanent solution, but it'll work for now.
To elaborate:
Line 2 of your js would go from
var days = '<option></option>',
to
var days = '<option> </option>',
and line 32 would go from }).parent().prepend('<span></span>'); to }).parent().prepend('<span> </span>');
Its for line height and your font size of page you can fix it by
Add line height style to your datePicker class like this:
line-height: 8px;
or change font-size like:
font-size: 10px;
Edit:
and for moving when you pick a some value from select you should set your span to position: absolute;
.datePicker > div > span{
position: absolute;
}
Edit2:
or you can set space value in first time in your span, change <span></span> to <span> </span>
Edit3:
i changed this lines to add space in initial between span tag, check values that add onload datepicker:
$.each(picker.children(), function () {
$(this).wrap('<div>').change(function () {
if ($(this).hasClass('month')) {
$(this).prev().html(months[$(this).val() - 1]);
} else {
$(this).prev().html($(this).val());
}
}).parent().prepend('<span> </span>');
if ($(this).hasClass('month')) {
$(this).prev().html(months[$(this).val()]?months[$(this).val()]:" ");
} else {
$(this).prev().html($(this).val()?$(this).val():" ");
}
});
Edit 4:
and css way, you can fixed it by add padding style to empty span like this:
.datePicker > div > span:empty{
padding:5px;
}
.datePicker > div {
display:inline;
position:relative;
min-width: 18px;
min-height:28px;
padding:0 5px 0 5px;
}
Just change display:inline-block to display:inline
The part about it appearing high I could fix with giving .datePicker select a 5px margin.

Coloring rows in a table with n colors

I know I can use odd and even to color alternating rows in a table. However, I'd like to be able to color every third row, so the coloring goes like red-green-blue-red-green-blue.
Furthermore, I'd like to make that general and use n colors to style every n:th row.
At the moment, I generate the table dynamically and for each iteration, I put in a class name like modulo0, modulo1 etc. on every td tag.
Is there a better way? A more automagical one, that is.
You want to use the :nth-child selector with 3n, a number can be added here to get every second starting from the start, second or third.
jsFiddle
HTML
<table>
<tr><td>R</td></tr>
<tr><td>G</td></tr>
<tr><td>B</td></tr>
<tr><td>R</td></tr>
<tr><td>G</td></tr>
<tr><td>B</td></tr>
</table>
CSS
tr:nth-child(3n+1) td {
background-color:red;
}
tr:nth-child(3n+2) td {
background-color:green;
}
tr:nth-child(3n) td {
background-color:blue;
}
Generally
More generally, replace 3 with the number of rows in which to change the colour.
tr:nth-child(2n) td { } /* every second row */
tr:nth-child(4n) td { } /* every fourth row */
tr:nth-child(10n) td { } /* every tenth row */
Support
Note that full support for CSS3 selectors only comes in at IE9. If support for IE8 is essential then an alternate solution is required, like manual classes or JavaScript.
Just use nth-child(3n+3). Keep in mind, that this is not a cross-browser solution. Here's a working example
May be the older way but if you don't have any problem with javascript can try below as well.
<body>
<script language="JavaScript" type="text/javascript">
function altrows(tableid,firstcolor,secondcolor,thirdcolor)
{
var rows = document.getElementById(tableid).getElementsByTagName("tr");
for(var i = 0; i < rows.length; i++)
{
i -= 1;
for (var b=0;b<=2;b++) {
i +=1;
if(b==0){ rows[i].bgColor = firstcolor; }
if(b==1){ rows[i].bgColor = secondcolor; }
if(b==2){ rows[i].bgColor = thirdcolor; }
}
}
}
</script>
<body onLoad="altrows('tb_detail','#FF0321','#44FF03','#2103FF')">
<table cellpadding="0" cellspacing="0" border="0" width="90%" id="tb_detail">
<tr><td>Item1</td></tr>
<tr><td>Item1</td></tr>
<tr><td>Item1</td></tr>
<tr><td>Item1</td></tr>
<tr><td>Item1</td></tr>
<tr><td>Item1</td></tr>
<tr><td>Item1</td></tr>
<tr><td>Item1</td></tr>
<tr><td>Item1</td></tr>
</table>
</body>

Table row - Giving alternate colors

In HTML, I am adding rows dynamically in a table
I need to give different colors for alternative rows using CSS
How can I acheive this?
To achieve this effect (known as zebra striping) in all browsers using just CSS you'll need to add a class to each row (e.g. odd and even) and give them different colours.
If you want to achieve this with just CSS and are not concerned with supporting older browsers (IE6-8) you should use the CSS3 nth-child pseudo element. This can achieve the required effect without the extra class mark-up, e.g.
tr:nth-child(odd) {
background-color: #FF0;
}
tr:nth-child(even) {
background-color: #F0F;
}
However if you want full browser support and don't mind using javascript there are a number of scripts available, both jQuery plugins and plain old javascript. Maybe try this for starters?
http://docs.jquery.com/Tutorials:Zebra_Striping_Made_Easy
Just create 2 css classes, and assign them to the tags alternately.
Try this using JQuery:
$('tr:even').css('background-color', 'grey');
See it in action here
What are you using to create the table, if it is rails you can use?:
= cycle('odd', 'even')
or you can do it in PHP like this:
$i = 0;
=($i++%2==1) ? 'odd' : 'even'
You can also try without CSS, its simple.
Code:
**var rowCount = document.getElementById("tableID").rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.style.backgroundColor = "yellow";
cell1.innerHTML = "hey";
var cell2 = row.insertCell(1);
cell2.style.backgroundColor = "green";
cell2.innerHTML = "hello";**
Here its creating dynamically row for the table and filling different color to coloumns.
hope this help..!!
Thanks
just create the css classes for rows(odd and even) but dont forget that the font color for text should be readeable regarding the background color
.row_odd{
background: #ffffff;
color: #000;
}
.row_even{
background: #faf8f5;
color: #000;
}
Then in the xhtml you have to set the class for each row. For example, using php while you are iterating on rows you can set the value of the variable $class.
<tr class="<?=$class?>" onmouseover="">
<td class="center col_check">...</td>
<td class="links">...</td>
<td class="center">...</td>
</tr>
In addition, you can make other css classes for each column depends of what you want!!

How can I set a <td> width to visually truncate its displayed contents?

I'm trying to set a column width of a table, which works fine until it gets to the point where child elements would be visually truncated ... then it won't size any smaller. ("visually truncated"-what doesn't fit appears to be hidden behind the next column)
Here is some sample code to demonstrate my problem:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
var intervalID = null;
function btn_onClick()
{
// keep it simple, only click once
var btn = document.getElementById("btn");
btn.disabled = true;
// start shrinking
intervalID = window.setInterval( "shrinkLeftCell();", 100);
}
function shrinkLeftCell()
{
// get elements
var td1 = document.getElementById("td1");
var td2 = document.getElementById("td2");
// initialize for first pass
if( "undefined" == typeof( td1.originalWidth))
{
td1.originalWidth = td1.offsetWidth;
td1.currentShrinkCount = td1.offsetWidth;
}
// shrink and set width size
td1.currentShrinkCount--;
td1.width = td1.currentShrinkCount; // does nothing if truncating!
// set reporting values in right cell
td2.innerHTML = "Desired Width : ["
+ td1.currentShrinkCount
+ "], Actual : ["
+ td1.offsetWidth + "]";
// Stop shrinking
if( 1 >= td1.currentShrinkCount)
window.clearInterval(intervalID);
}
</script>
</head>
<body>
<table width="100%" border="1">
<tr>
<td id="td1">
Extra_long_filler_text
</td>
<td id="td2">
Desired Width : [----], Actual : [----]
</td>
</tr>
</table>
<button id="btn" onclick="btn_onClick();">Start</button>
</body>
</html>
I've tried setting the width in different ways including
td1.offsetWidth = td1.currentShrinkCount;
and
td1.width = td1.currentShrinkCount + "px";
and
td1.style.width = td1.currentShrinkCount + "px";
and
td1.style.posWidth = td1.currentShrinkCount;
and
td1.scrollWidth = td1.currentShrinkCount;
and
td1.style.overflow = "hidden";
td1.width = td1.currentShrinkCount;
and
td1.style.overflow = "scroll";
td1.width = td1.currentShrinkCount;
and
td1.style.overflow = "auto";
td1.width = td1.currentShrinkCount;
I realize, I could probably use DIV's, but I'd prefer not to since the table is being generated from a bound control, and I don't really want to get into rewriting asp.net controls.
Having said that, I thought as a last ditch effort, I could at least wrap each 'td1's contents with a DIV, and the overflow would take care of things, but even replacing
<td id="td1">
Extra_long_filler_text
</td>
with
<td id="td1" style="overflow:hidden;">
<div style="margin=0;padding:0;overflow:hidden;">
Extra_long_filler_text
</div>
</td>
didn't work.
Does anybody know how I can set a width to visually truncate its contents?
BTW-My target browser is IE7. Other browsers are not important right now, since this is an internal app.
I just tried adding table-layout: fixed; to the <table> and it worked for me on IE7.
In a fixed table layout, the horizontal layout only depends on the table's width, the width of the columns, and not the content of the cells
Check out the documentation.
CSS Solution
"Truncate" may not be the word you are looking for. You may just want to hide the overflowing characters. If that is the case, look into the css-property "overflow," which will hide any content extending past the declared limits of its container.
td div.masker {
height:25px;
width:100px;
overflow:hidden;
}
<td>
<div class="masker">
This is a string of sample text that
should be hidden when it reaches out of the bounds of the parent controller.
</div>
</td>
Javascript Solution
If you are indeed wanting to truncate the text within the container, you will have to remove one character from the right, test the width of the parent, and continue to remove characters and testing the parent width until the parent width matches the declared width.
while (parent.width > desiredWidth) {
remove one char from right-side of child-text
}
<td id="td1" style="overflow-x:hidden;">
Should be
<td id="td1" style="overflow:hidden;">
overflow-x is a Microsoft CSS attribute, which is now part of CSS3. I would stick with the older overflow attribute.
EDIT:
As Paolo mentions you also need to add table-layout:fixed; and specify the width of the table. A full example follows.
<html>
<head>
<style>
table
{
table-layout:fixed;
width:100px;
}
td
{
overflow:hidden;
width:50px;
border-bottom: solid thin;
border-top:solid thin;
border-right:solid thin;
border-left:solid thin;
}
</style>
</head>
<body>
<table>
<tr><td>Some_long_content</td><td>Short</td></tr>
</table>
</body>
</html>
As far as I know, a table cell will always stretch to accommodate its contents.
Have you thought about using Javascript to dynamically truncate the data in table cells that have more than a certain amount of content? Alternatively, you could do this more easily server side.
You could use jQuery or plain javascript to surround the content of your cell(s) with div tags and set a fixed width and overflow:hidden on those instead. Not beautiful, but it'd work.
ETA:
<td><div style="width:30px;overflow:hidden">Text goes here</div></td>
Since the DIV is the bounding element, that's where the width should be set.