Search code examples
htmlcsshtml-tablecontenteditable

Fixed width on second td in editable table


I want to have a fixed width for my editable table, but I also wanting to set different width for each TD. In my attempt I am able to get the table set at a fixed width, but this causes the width of the TDs appear to be 50% instead of the 80% - 20% I had before setting the fixed width

CSS

table {
  margin: 15px 0;
  border: 1px solid black;
  table-layout: fixed;
  width: 100%;
}
.fixed td:nth-of-type(1) {width:20%;}
.fixed td:nth-of-type(2) {width:80%; text-align: left;}
.fixed {
margin:0px;padding:0px;
width:100%;

    border:1px solid #000; }
.fixed td {
margin:0px;padding:0px;
width:100%;
    border:1px solid #000; }

HTML

<div class="fixed" contenteditable="true">
<table>
    <tbody>
<tr>
            <td colspan="2">Header:</td>

</tr>
        <tr>
            <td>Name:</td>
            <td><br/></td>
</tr>
        <tr>
            <td>DOB::</td>
            <td><br/></td>
</tr>
        <tr>
            <td>Comments:</td>
            <td><br/></td>
</tr>

        </table>

What am I missing? Check this Fiddle if it will help. Try it out by typing enough to see it automatically goes to the next line after a certain point.


Solution

  • The problem with your code is that your first <tr> is having colspan="2". So when you give a width:100% to all the TDs of the table, the css won't get applied to the underlying TDs as you want.

    Your solution is to separate the Header td: <td colspan="2">Header:</td> into a separate table (Refer HTML-1 below) or put the underlying TDs in the same TR as that of the header (Refer HTML-2 below).

    Also change the CSS and simplify it like I did below. you have written a lot of unnecessary CSS.

    Working Fiddle Here

    Here's what I tried. try this:

    HTML-1:

    <table class="fixed" >
        <tbody>
        <tr>
            <td colspan="2">Header:</td>
        </tr>
        </tbody>
    </table>
    <table  class="fixed" >
        <tbody>
        <tr>
            <td>Name:</td>
            <td>test</td>
        </tr>
        <tr>
            <td>DOB::</td>
            <td>tes</td>
        </tr>
        <tr>
            <td>Comments:</td>
            <td>test</td>
        </tr>
    </table>
    

    HTML-2:

    <table class="fixed" >
    <tbody>
      <tr>
            <td colspan="2">Header:</td>
        <tr>
            <td>Name:</td>
            <td>test</td>
        </tr>
        <tr>
            <td>DOB::</td>
            <td>tes</td>
        </tr>
        <tr>
            <td>Comments:</td>
            <td>test</td>
        </tr>
     </tr>
    </tbody>
    </table>
    

    Simplified CSS:

    table {
      margin: 0 0;
      width: 100%;
      table-layout: fixed;
    }
    
    .fixed td:nth-of-type(1) {width:80%;}
    .fixed td:nth-of-type(2) {width:20%; text-align: left;}
    
    .fixed td {
    margin:0px;padding:0px;
    border:1px solid #000; }