How to create a diagonal line within a table cell?

I don’t know if is the best way, but I can’t do that with CSS. My answer is in jQuery:

http://jsfiddle.net/zw3Ve/13/

$(function(){
    $('.crossOut').each(function(i){
        var jTemp = $(this),
            nWidth = jTemp.innerWidth(),
            nHeight = jTemp.innerHeight(),
            sDomTemp = '<div style="position:absolute; border-color: transparent black white white; border-style:solid; border-width:'+nHeight +'px '+nWidth +'px 0px 0px; width:0; height:0; margin-top:-'+nHeight+'px; z-index:-2"></div>';

        sDomTemp += '<div style="position:absolute; border-color: transparent white white white; border-style:solid; border-width:'+nHeight +'px '+nWidth +'px 0px 0px; width:0; height:0; margin-top:-'+(nHeight-1)+'px; z-index:-1"></div>';

        jTemp.append(sDomTemp);
    });
});

or

http://jsfiddle.net/zw3Ve/16/ (with CSS class cleaner)

CSS part:

.crossOut .child{
    position:absolute; 
    width:0; 
    height:0;
    border-style:solid;
}
.crossOut .black-triangle{
    z-index:-2;
    border-color: transparent black white white;
}
.crossOut .white-triangle{
    border-color: transparent white white white;
    z-index:-1;
}

jQuery code:

$(function(){
    $('.crossOut').each(function(i){
        var jTemp = $(this),
            nWidth = jTemp.innerWidth(),
            nHeight = jTemp.innerHeight(),
            sDomTemp = '<div class="child black-triangle" style="border-width:'+nHeight +'px '+nWidth +'px 0px 0px; margin-top:-'+nHeight+'px; "></div>';

        sDomTemp += '<div class="child white-triangle" style="border-width:'+nHeight +'px '+nWidth +'px 0px 0px; margin-top:-'+(nHeight-1)+'px;"></div>';

        jTemp.append(sDomTemp);
    });
});

The good thing is it works with any width and height of a table cell.

Edit:

I was not happy with the quality of rendering of triangles made ​​with CSS borders so I used the css-rotation. I think this is a better work (and the lines are render better):

http://jsfiddle.net/zw3Ve/21/

(Using -sand-transform is for IE6, so it use is optional.)

Edit2:
The last version has not got support for IE7-IE8 (seems the -sand-transform only works in CSS styles and not in styles written by JavaScript). I made a version with compatibility with old browsers:

http://jsfiddle.net/zw3Ve/23/

Leave a Comment