Skip to content
Advertisement

Keep the height/width ratio of table

I have a simple table design, a square with 3×3 cells -think Rubik’s cube. I want this table’s width to always be 30% of the window and I don’t want the height/width ratio change if the browser window is being resized. Also I want the inner 3×3 cells to be able to keep text and/or images without the symmetry being distorted. Is this possible with only css/javascript? I’ve tried sooooooooo many things but none has been working so far.

EDIT: I’ve added one of my many attempts to solve this below. The code works in Chrome when I try it in the broswer… but not here for some reason. However, it didn’t solve my initial problem so I guess it’s no problem.

       function getTableWidth(){
        var element = document.getElementById("table");
        var intElemClientWidth = element.clientWidth;
        document.getElementById("table").style.height=intElemClientWidth;
}
   
    .cell{ 
    height: 33%;
    width: 33%;
<div onclick="getTableWidth()">Get 1:1 ratio</div>
    
<table id="table" width="30%" border="1">
  <tbody>
    <tr>
      <td class="cell">1</td>
      <td class="cell">2</td>
      <td class="cell">3</td>
    </tr>
    <tr>
       <td class="cell"></td>
      <td class="cell"></td>
      <td class="cell"></td>
    </tr>
    <tr>
      <td class="cell"></td>
      <td class="cell"></td>
      <td class="cell"></td>
    </tr>
  </tbody>
</table>

Advertisement

Answer

I see what you mean. Let me provide a modified solution from here: html make <td> height proportional to the width

table {
  width: 30%;
}

td {
  border: 1px solid black;
  position: relative;
}

td > div {
  position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

td:before {
    content: "";
    display: block;
    padding-top: 100%;
}
<table>
      <tr>
        <td><div>1</div></td>
        <td><div>2</div></td>
        <td><div>3</div></td>
      </tr>
      <tr>
        <td><div>1</div></td>
        <td><div>2</div></td>
        <td><div>3</div></td>
      </tr>
      <tr>
        <td><div>1</div></td>
        <td><div>2</div></td>
        <td><div>3</div></td>
      </tr>
</table>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement