Make an HTML table more readable on mobile devices by using the ::before pseudo-element. We add labels to each cell, so they appear like cards when the table is viewed on smaller screens. The ::before content is set using a data-label attribute for each cell to enhance mobile viewability without horizontal scrolling.
Transcript
[00:01] Here we have an HTML table. If we inspect, you'll see it's a regular table tag with all of the table children, thead, thebody, table rows, and table cells. If we squish this table down, it starts to get a little ugly. It's not so bad with three columns, So let's add a couple more. Let's add website, favorite color, and is active.
[00:40] Let's make sure to add our columns. So here we have a website, a favorite color is active. We'll add our data. So, John's favorite color is blue, Jane's favorite color is green, and Doe's favorite color is red. And then a little variation on Is Active.
[01:08] Back in the browser, you can see that the mobile table got much more illegible. You have to horizontally scroll to see all of the columns. The date of birth is super squished, and overall it's just a horrible experience. What would be nicer is if each row in this table was its own card and each cell had its label in the card, we'd take away this header. Back in our code, I'm going to go over to our table component.
[01:49] Here's our table cell. I'm going to paste a little bit of CSS. This CSS is turning the table cell into a flex column. When it's medium width, it turns it back into a table cell, so the browser will treat it as a table cell. It reverts the justify content.
[02:17] The other thing that we're doing is we're adding this before label. The before content will be whatever we set data label to on this table cell. On this table cell. We break the words and then we added CSS to make this before label look like our table header. So over in our app, we need to add the data label to our table cell.
[02:55] So here, in this case, the header is going to be the data label. So over in our browser, you'll see we have nice labels on each row of data. And now the data is all stacked on each other and you can style this like a card. One thing that we need to do is get rid of the table header when we're on the mobile screen. So let's go into our table header.
[03:35] We will add hidden, and on medium screens, we'll add table header group. So in our browser, we got rid of the table header, and now our table looks a lot better on a mobile screen.