user780483
user780483

Reputation: 3063

Style CSS table td

My site allows users to generate tables with PHP. The number of rows and cells is variable but the number of columns is always fixed. The table usually generates two digit numbers. When the table generates three digit numbers the entire table expands to accommodate this and the size of the table increases, ruining my layout. Is there a way to use CSS and style this table's tds so that the table doesn't change size when 3 digit numbers are generated. (3 digits are the longest). I tried adding padding to the table, but its not working.

Also, should I use an id in table or class?

Upvotes: 4

Views: 32811

Answers (3)

David Thomas
David Thomas

Reputation: 253485

You could use a combination of width and max-width:

td {
    border: 1px solid #ccc;
    width: 2em; /* or whatever... */
    max-width: 2em; /* or whatever... */
    height: 2em; /* or whatever... */
    line-height: 2em; /* or whatever... */
    text-align: center; /* a personal aesthetic choice... */
    overflow: hidden; /* to prevent overflow... */
}

JS Fiddle demo.

(Please note that while I use jQuery in the demo, that's only to generate contents and isn't necessary for the demo to work.)

Upvotes: 3

jpm
jpm

Reputation: 3155

td {
  width: 50px;
}

I think something like that might work for you. Obviously, you can adjust the actual width to your needs.

And if you multiple table and only want to fix one, give the one in question an id:

<table id="fixed_table">

and then in the css, you could say:

#fixed_table td {
  width: 50px;
}

and it would only affect tds in that particular table. Of course, if you wanted to affect some tables but not others, you would use a class instead of an id.

Upvotes: 11

joakimdahlstrom
joakimdahlstrom

Reputation: 1595

Set fixed widths on the columns.

Upvotes: 2

Related Questions