AazibCh AazibCh - 3 months ago 8
CSS Question

Why is the size of the <td>s changing when border is added inside it using the box-sizing property?

I'm using the

.click
JQuery method to add
.clicked
to
<td>
whenever it is clicked.
.clicked
contains a border and the
box-sizing
property set to
border-box
.

When I click two consecutive
<td>
s either horizontally or vertically, their size seems to change. Why is it so?

Here's my code:

<!-- page.html -->

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>

/* stylesheet.css */

td {
height: 100px;
width: 100px;
background-color: red;
}

.clicked {
border: 5px solid green;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}

// script.js

$(document).ready(function () {
$("td").click( function() {
$(this).addClass("clicked");
});
});


Help shall be appreciated.

Answer

Padding (which isn't counted by box-sizing: border-box is messing things up. Your td's have a padding of 1px if you set this to 0 then the weird behaviour goes away.

https://jsfiddle.net/x11us50v/