Search code examples
javascriptcsswidth

how to make CSS width property equal to the result of a mathematical expression


I'm trying to make the width property equal to (100/3)% because I am trying to divide the width evenly amongst 3 columns. But obviously this is not valid css. What is the proper way to accomplish this?

enter image description here


Solution

  • pure CSS method:

    th, td {
      width: calc(100% / 7);
    }

    Javascript method: You can get your table elements and assigns styles, try this:

    let th = document.getElementsByTagName('th');
    let td = document.getElementsByTagName('td');
    
    console.log(th, td)
    
    for(let el of th){
        el.style.width = (100 / 3) + 'px';
    }
    
    for(let el of td){
        el.style.width = (100 / 3) + 'px';
    }
    <table>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Age</th>
      </tr>
      <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
      </tr>
      <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
      </tr>
    </table>