Search code examples
javascripthtmlcsshtml-tablescreen-size

Shrink and expand table width as screen width changes


I want to be able to shrink the width of my table as the screen width decreases and expand the width of the table when the screen width increases.
I know that I can use @media() in both CSS and JavaScript but I'm trying to find a simpler way to do this.
The current issue that I am having is that another div outside of the parent div of my table is overlapping the table when the screen width shrinks.

Here is the CSS for my table:

#course_table {
  margin: auto;
  font-family: "Lato","Helvetica Neue",Helvetica,Arial,sans-serif;
  border-collapse: collapse;
  padding: 12px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.3);
  border-radius: 4px;
  width: 100%;
}

Solution

  • sample code with vw unit

    body { margin: 0;}
    * { box-sizing: border-box; }
    
    Table { border-collapse: collapse; margin: 0;   }
    td    { border: 1px solid grey; padding: 2px 10px; }
    thead { background-color: turquoise;}
    
    table tr td:nth-child(1) { width: 30vw }
    table tr td:nth-child(2) { width: 10vw }
    table tr td:nth-child(3) { width: 60vw }
    <table>
      <thead>
        <tr><td>A</td><td>B</td><td>C</td></tr>
      </thead>
      <tbody>
        <tr><td>1</td><td>2</td><td>3</td></tr>
      </tbody>
    </table>

    PS: using magic words is not prohibited here...