Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a CSS table fit the screen width?

Currently the table is too wide and causes the browser to add a horizontal scroll bar.

like image 366
David B Avatar asked Nov 21 '10 08:11

David B


People also ask

How do you make a table fit the screen in HTML?

To make an HTML table tit the screen: Set the width to 100%, so that your code will look like this: <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td>My html table is set to fit the screen</td> </tr> ...


2 Answers

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.

like image 147
Avatar Avatar answered Sep 27 '22 03:09

Avatar


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 old nowrap attribute, &nbsp;, a nobr 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.

like image 23
T.J. Crowder Avatar answered Sep 26 '22 03:09

T.J. Crowder