Responsive table using CSS display: table-row
I'm having trouble converting my spreadsheet to a more responsive design, I've tried a lot of resources on google but they're all limited and don't work as intended. The main problem I am facing is that my tables are dynamically generated and I don't want to edit the resources I find on Google, so I can update them easily and not mess with the code too much.
Anyway, my desk has a very simple design. There are 5 columns with X rows (depending on what is being generated from the database). Whenever the user resizes his browser (or when he is using a mobile phone), I want to resize my table to fit smaller screens. An example of this would be:
Desktop
Header 1 | Header 2 | Header 3
------------------------------
Content | Content | Content
Telephone
Header 1 | Content
------------------
Header 2 | Content
------------------
Header 3 | Content
I am trying to accomplish this using display: table-row
using CSS whenever the screen reaches a certain width, I created this jsfiddle to display my current code. However, currently th
and are td
displayed vertically above / below each other, and not next to each other as I assumed. I tried using float: left
and float: right
, but it doesn't work (see Jsfiddle). Can anyone help me accomplish what I want to use CSS? And if that is not possible, how do I navigate using Javascript to do this, bearing in mind that my tables will not be generated on page load (some are dynamically added to the page)?
source to share
How about setting definitions table
for different screen widths. It also prevents any unintended side effects of your elements floating around.
Volatile script
.table {
display: table;
width: 100%;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
}
@media screen and (max-width: 750px) {
.cell {
display: block;
}
.row {
display: table-cell;
width: 50%;
}
}
<div class="table">
<div class="row">
<div class="cell">Head #1</div>
<div class="cell">Head #2</div>
<div class="cell">Head #3</div>
<div class="cell">Head #4</div>
</div>
<div class="row">
<div class="cell">Content #1</div>
<div class="cell">Content #2</div>
<div class="cell">Content #3</div>
<div class="cell">Content #4</div>
</div>
</div>
source to share
I split you into a violin. This is how I would solve it:
Html
<div class="row">
<span>Head #1</span>
<span>Head #2</span>
<span>Head #3</span>
<span>Head #4</span>
</div>
<div class="row">
<span>Content #1</span>
<span>Content #2</span>
<span>Content #3</span>
<span>Content #4</span>
</div>
CSS
.row
{
display: table-row;
}
.row > *
{
display: table-cell;
}
@media screen and (max-width: 750px) {
.row
{
display: block;
float: left;
}
.row > *
{
display: block;
}
}
source to share