Roman Grinyov
Roman Grinyov

Reputation: 282

Shift table border when adding absolutely positioned pseudo-element to <tr>

There is a table. I am adding via JS rows. To new rows through ::after I add a cross "Delete row"; the pseudo-element is absolutely positioned, but the first time a new row is added, the table border is shifted. I can't figure out why, because the ::after pseudo-element is absolutely positioned and shouldn't affect the rendering of the elements.

const tbody = document.querySelector('tbody');

document.querySelector('button').addEventListener('click', event => {
  const tr = tbody.querySelector('tr:last-child').cloneNode(true);
  tbody.appendChild(tr);
});
table {
  border: 1px solid #000;
  border-spacing: 10px;
}

td {
  border: 1px solid #000;
  height: 50px;
  width: 50px;
}

tr:nth-child(n + 3) {
  position: relative;
}

tr:nth-child(n + 3)::after {
  color: #f00;
  content: '×';
  display: block;
  font-weight: bold;
  height: 10px;
  width: 10px;
  position: absolute;
  top: 30%;
  right: -3%;
}
<table>
  <tbody>
    <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  </tbody>
</table>
<br>
<button>Add row</button>

https://jsfiddle.net/0qhv5n3g

Upvotes: 1

Views: 127

Answers (1)

C3roe
C3roe

Reputation: 96407

Pseudo elements created by ::after are supposed to behave, as if an actual child element was inserted into the element. Table rows have table cells as children - so you basically created an additional table cell.

Put the pseudo element into the last table cell instead:

tr:nth-child(n + 3) td:last-child::after { ... }

Upvotes: 1

Related Questions