简体   繁体   中英

Prevent table from resizing when adding border to specific cell

Here is my code. The problem is: When i click a td cell, add border to it, and the border makes the table changes size.

For some reasons, i dont want the table increase its size when adding border to td tag, and i can not use outline in css.

I tried to add this line of css code: box-sizing: border-box; but it does not seem to work.

Thank you for any idea!!

 Array.prototype.forEach.call( document.querySelectorAll('td'), function(td) { td.addEventListener('click', function(e) { e.target.classList.add('myBorder') }) })
 table { border-collapse: collapse; } th, td { border: 1px solid black; box-sizing: border-box; }.myBorder { border: 2px solid #4b89ff; }
 <table> <thead> <tr> <th>id</th> <th>Name</th> <th>Gender</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Bob</td> <td>Male</td> </tr> <tr> <td>2</td> <td>Anna</td> <td>Female</td> </tr> <tr> <td>3</td> <td>Christ</td> <td>Male</td> </tr> </tbody> </table>

Inspecting the td with Chrome i found that adding the class to the cell was also generating a padding of 1px. And if you set padding-bottom: 0px; on.myBorder class will solve the problem.

 Array.prototype.forEach.call( document.querySelectorAll('td'), function(td) { td.addEventListener('click', function(e) { e.target.classList.add('myBorder') }) })
 table { border-collapse: collapse; } th, td { border: 1px solid black; }.myBorder { border: 2px solid #4b89ff; padding-bottom: 0px; }
 <table> <thead> <tr> <th>id</th> <th>Name</th> <th>Gender</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Bob</td> <td>Male</td> </tr> <tr> <td>2</td> <td>Anna</td> <td>Female</td> </tr> <tr> <td>3</td> <td>Christ</td> <td>Male</td> </tr> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM