Search code examples
htmlcsswidthcss-tables

Make HTML table wide enough to fit content


I run a script that generates an HTML page, but I can't correctly format the table that is generated. need to make a table that spans as wide as necessary. Currently, I have to specify a specific width (1500px) so that the contents of each cell do not wrap to the next line. Here is an example:

With width set to 1500px:
+-----------------------------+------------------------------+
|Contents of my cell          | Contents of other cell       |
+-----------------------------+------------------------------+

With width set to 100%:
+-------------------+--------------------+
|Contents of my     |Contents of other   |
|cell               |cell                |
+-------------------+--------------------+

Ideally, I the text wouldn't wrap (eg. when width is set to 1500px) but wouldn't have to set a static table width. At times, the table may need to be wider (or smaller) than 1500, so I would like the width to be as dynamic as possible.

This is the CSS I'm currently using:

<style type="text/css">
h1 {
    text-shadow: rgba(255, 255, 255, 0.796875) 0px 1px 0px;
    font-family: Georgia,"Times New Roman","Bitstream Charter",Times,serif;
    font-weight: normal;
    padding: 7px 7px 8px;
    text-align: left;
    line-height: 1.3em;
    font-size: 24px;
}
table {
    border: 1px solid #DFDFDF;
    background-color: #F9F9F9;-moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
    font-family: Arial,"Bitstream Vera Sans",Helvetica,Verdana,sans-serif;
    color: #333;
    width: 1500px;
}
th {
    text-shadow: rgba(255, 255, 255, 0.796875) 0px 1px 0px;
    font-family: Georgia,"Times New Roman","Bitstream Charter",Times,serif;
    font-weight: normal;
    padding: 7px 7px 8px;
    text-align: left;
    line-height: 1.3em;
    font-size: 14px;
    color: #555;
}
td {
    font-size: 12px;
    padding: 4px 7px 2px;
    vertical-align: bottom;
    border-right: 1px solid #DFDFDF;
}
</style>

Any ideas on how I can do this?


Solution

  • If you are trying to make it so the line never wraps, try white-space:nowrap and drop the width from your table.

    td {
        font-size: 12px;
        padding: 4px 7px 2px;
        vertical-align: bottom;
        border-right: 1px solid #DFDFDF;
        white-space:nowrap;
    }