Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert columns to rows using CSS

Hi I need to convert columns to rows and rows to columns. I have both column headers and rows headers to the left. The row headers are just bold text to the left of the row to define what the row is.

I am trying to make this table mobile friendly. The table is 7 columns wide and the 7 columns do not show in a smart phone. So my idea is to use a media query to display a table where the columns and rows are switched since there will be no more than 3 rows. Can this be done?

like image 586
Luke101 Avatar asked May 09 '14 04:05

Luke101


People also ask

How do I change a row to a column in CSS?

You can do it using display: flex . This code works when viewport width is less than 500px. Should set table and td to be display: block; to be safe.


1 Answers

DEMO

Css Solution: Simply turn your td & th to display:block; & your tr to display:table-cell;

CSS:

@media screen and (max-width:767px) {
    table tr > *{
        display: block;
    }
    table tr {
        display: table-cell;
    }
}

Drawback: If your cells have too much data the layout will break Example.

jQuery Solution: We can keep track of element height to stay the same DEMO

JS:

$(function () {
    switchRowsAndCols("table", 767);
});

function switchRowsAndCols(thisTable, resolution) {
    if ($(window).width() < resolution) {
        switchRowsAndColsInnerFun(thisTable);
    }
    $(window).resize(function () {
        if ($(window).width() < resolution) {
            switchRowsAndColsInnerFun(thisTable);
        }else{
            switchRowsAndColsRemove(thisTable);
        }
    });
};

function switchRowsAndColsRemove(thisTable) {
    $("tr > *", thisTable).css({
        height: 'auto'
    });
};

function switchRowsAndColsInnerFun(thisTable) {
    var maxRow = $("tr:first-child() > *", thisTable).length;

    for (var i = maxRow; i >= 0; i--) {

        $("tr > *:nth-child(" + i + ")", thisTable).css({
            height: 'auto'
        });

        var maxHeight = 0;

        $("tr > *:nth-child(" + i + ")", thisTable).each(function () {
            var h = $(this).height();
            maxHeight = h > maxHeight ? h : maxHeight;
        });

        $("tr > *:nth-child(" + i + ")", thisTable).each(function () {
            $(this).height(maxHeight);
        });
    };
};
like image 69
Imran Bughio Avatar answered Nov 04 '22 11:11

Imran Bughio