Tim Butterfield
Hide/Show Content Based on Screen Size

A useful tool for optimizing a webpage for mobile devices. The idea is to hide or show content based on the screen size of the users device using display:none;.

HTML

As an example, we can swap which table we are looking at. Below is the HTML that will be used.

<table class="desktop">
<tr><td>
<h1>Desktop</h1>
</td></tr>
</table>
<table class="mobile">
<tr><td>
<h1>Mobile</h1>
</td></tr>
</table>

CSS

The mobile table will need to be switch off as an initial rule. Using the !important rule, this code will be given authority over any other display instance. This can only be overwritten buy another !important rule.

.mobile {
display:none !important;
}

With this code below, any screen up to 480px in width will initiate the css rules within. In this case, there are table rules which switch off the desktop table and switch on the mobile table. This function works like a toggle switch and will revert to normal if the screen size changes above 480px.

@media only screen and (max-width: 480px) {
table[class="desktop"] {
display:none !important;
}
table[class="mobile"] {
display:block !important;
}
}

This is not limited to tables or display:none;. This can be used to change floats, img widths, fonts etc. Also, you can change the screen size.