How can I make a CSS table fit the screen width?
If the table content is too wide (as in this example), there's nothing you can do other than alter the content to make it possible for the browser to show it in a more narrow format. Contrary to the earlier answers, setting width to 100% will have absolutely no effect if the content is too wide (as that link, and this one, demonstrate). Browsers already try to keep tables within the left and right margins if they can, and only resort to a horizontal scrollbar if they can't.
Some ways you can alter content to make a table more narrow:
- Reduce the number of columns (perhaps breaking one megalithic table into multiple independent tables).
- If you're using CSS
white-space: nowrap
on any of the content (or the oldnowrap
attribute,
, anobr
element, etc.), see if you can live without them so the browser has the option of wrapping that content to keep the width down. - If you're using really wide margins, padding, borders, etc., try reducing their size (but I'm sure you thought of that).
If the table is too wide but you don't see a good reason for it (the content isn't that wide, etc.), you'll have to provide more information about how you're styling the table, the surrounding elements, etc. Again, by default the browser will avoid the scrollbar if it can.
CSS:
table {
table-layout:fixed;
}
Update with CSS from the comments:
td {
overflow: hidden;
text-overflow: ellipsis;
word-wrap: break-word;
}
For mobile phones I leave the table width but assign an additional CSS class to the table to enable horizontal scrolling (table will not go over the mobile screen anymore):
@media only screen and (max-width: 480px) {
/* horizontal scrollbar for tables if mobile screen */
.tablemobile {
overflow-x: auto;
display: block;
}
}
Sufficient enough.
table { width: 100%; }
Will not produce the exact result you are expecting, because of all the margins and paddings used in body. So IF scripts are OKAY, then use Jquery.
$("#tableid").width($(window).width());
If not, use this snippet
<style>
body { margin:0;padding:0; }
</style>
<table width="100%" border="1">
<tr>
<td>Just a Test
</td>
</tr>
</table>
You will notice that the width is perfectly covering the page.
The main thing is too nullify the margin
and padding
as I have shown at the body, then you are set.