Home > Software engineering >  Is it possible to have a contenteditable div inside a table cell stick to its original cell dimensio
Is it possible to have a contenteditable div inside a table cell stick to its original cell dimensio

Time:12-08

I'm making an editable cell within a table, however despite overflow: auto css typing in there just makes it expand in a very awkward way.

How do I make it stick to the initial cell size, with scroll bars appearing as needed? Preferably this needs to be without set pixel values for width/height, so the whole table will stay on-screen between different resolutions or zooming in and out (control mousewheel).

The code below can be found & run here: https://codepen.io/Dr_MR/pen/BawKNEy

html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
html,
.table {
  width: 100%;
  height: 100%;
  border: 1px solid #000;
}
cell {
  overflow: auto;
}
<table class="table">
  <tr>
    <th>Person 1</th>
    <th>Person 2</th>
    <th>Person 3</th>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td>Linus</td>
  </tr>
  <tr>
    <td>
      <div contenteditable="true" class="cell">Editable cell</div>
    </td>
    <td>14</td>
    <td>10</td>
  </tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Instead of using a <div> with contenteditable="true", you can use a <textarea> which shows scrollbars once the text goes beyond the boundaries like below.

TIP: Using <textarea>, you can increase the number of rows that are visible by default.

html {
  box-sizing: border-box;
}
*,
*:before,
*:after {
  box-sizing: inherit;
}
html,
.table {
  width: 100%;
  height: 100%;
  border: 1px solid #000;
}
cell {
  overflow: auto;
}
<table class="table">
  <tr>
    <th>Person 1</th>
    <th>Person 2</th>
    <th>Person 3</th>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td>Linus</td>
  </tr>
  <tr>
    <td>
      <textarea id="w3review" name="w3review" rows="3" cols="50">Editable Text.</textarea>
    </td>
    <td>14</td>
    <td>10</td>
  </tr>
</table>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Instead of <table>, try using CSS-Grids, as they have the ability to have fixed size and you can do exactly what you ask.

Good resources to start with it are:

NOTE: I understand that I don't answer the question as is, but I try to push CSS grids every time someone uses HTML tables for display and alignment, as CSS should be used instead.

  • Related