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?
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.
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);
});
};
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With