user3185872
user3185872

Reputation: 25

HTML/CSS adjust table width to column width not the oposite way

How do I make column width stop adjust to table width because following code will stretch columns past 50px when rendered:

<style>
   table {
      width:2000px;
   }

   td {
      width:50px;
   }
</style>

<table border="1">
   <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
   </tr>      
</table>

then second question is opposite if I have no width set for table and have each column set to 200px how I make it build big table that's larger than screen. When I render below code table width adjusted to page width (100%) and each column has equal width within table not 200px

<style>
   td {
      width:200px;
   }
</style>

<table border="1">
   <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
   </tr>      
</table>

Upvotes: 0

Views: 1561

Answers (2)

bugovicsb
bugovicsb

Reputation: 456

  1. display: inline-block; will solve it

    td {
        width:50px;
        display: inline-block;
        /* if you want to write text in the cells longer than 50px, use also the followings */
        overflow: hidden;
        white-space: nowrap;
    }
    
  2. table-layout: fixed; will solve it

    table {
        table-layout: fixed;
        width: 1px; /* required for table-layout */
    }
    
    td {     
        width:200px;
    }
    

Upvotes: 0

BKCOHEN
BKCOHEN

Reputation: 114

Question 1: Removing the table width as you did in Q2 will solve this.

Question 2: You will need to check your containers because your table and columns will size to their container not the screen.

Ex:

body {
width:1000px;
}

OR

container{width:1200px;}

either of these or something similar will contain your table and not allow it's width to continue.

Upvotes: 1

Related Questions