Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make contenteditable respect the initial size of a table cell?

My table has 3 cells: the first two contain inputs, and the third one has my contenteditable. Each cell has a width of 33.333%. When I type text into an input and it overflows, everything works fine — the text is simply hidden, as expected for an input.

However, when I type into the contenteditable, it stretches the cell instead of "scrolling" the text like an input does.

enter image description here

* {
  box-sizing: border-box;
}

table {
  width: 100%;
}

td {
  width: 33.333333%;
}

input {
  width: 100%;
  height: 32px;
  border: 1px solid #dedede;
}

.contendeditable {
  padding-left: 10px;
  height: 32px;
  border: 1px solid red;
  width: 100%;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  line-height: 32px;
}
<table>
  <tr>
    <td><input type="text" /></td>
    <td><input type="text" /></td>
    <td>
      <div class="contendeditable" contenteditable="true"></div>
    </td>
  </tr>
</table>

Here is the jsfiddle: https://jsfiddle.net/zvm0exdc/14/

like image 305
Seredniy Avatar asked Sep 02 '25 14:09

Seredniy


1 Answers

By default tables follow the 'auto' layout. This layout resizes the columns upon input. This is causing your widths to not be respected, and the overflow is never applied cause it is considered as valid layout.

You need to specify add table-layout: fixed on your table's css when you want the the rules to be respected when content changes.

table {
  width: 100%;
  table-layout: fixed
}

* {
  box-sizing: border-box;
}

table {
  width: 100%;
  table-layout: fixed;
}

td {
  width: 33.333333%;
}

input {
  width: 100%;
  height: 32px;
  border: 1px solid #dedede;
}

.contendeditable {
  padding-left: 10px;
  height: 32px;
  border: 1px solid red;
  width: 100%;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  line-height: 32px;
}
<table>
  <tr>
    <td><input type="text" /></td>
    <td><input type="text" /></td>
    <td>
      <div class="contendeditable" contenteditable="true"></div>
    </td>
  </tr>
</table>
like image 155
Frox Avatar answered Sep 05 '25 05:09

Frox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!