On click I am adding, 1px border to div, so Div size increases by 2px X 2px. I dont want to get div size increased. Is there any simple way to do so?
I needed to be able to "border" any element by adding a class and not affect its dimensions. A good solution for me was to use box-shadow. But in some cases the effect was not visible due to other siblings. So I combined both typical box-shadow as well as inset box-shadow. The result is a border look without changing any dimensions.
Values separated by comma. Here's a simple example:
.add_border {
box-shadow:-1px 0 1px 1px rgba(0, 0, 0, 0.75), inset -1px 0 0 1px rgba(0, 0, 0, 0.75);
}
jsfiddle
Adjust for your preferred look and you're good to go!
You can do some fancy things with inset shadows. Example to put a border on the bottom of an element without changing its size:
.bottom-border {
box-shadow:inset 0px -3px 0px #000;
}
Try this
box-sizing: border-box;
We can also use css calc() function
width: calc(100% - 2px);
subtracting 2px for borders
You can create the element with border with the same color of your background, then when you want the border to show, just change its color.
I usually use padding to resolve this issue. The padding will be added when border disappears and removed when border appears. Sample code:
.good-border {
padding: 1px;
}
.good-border:hover {
padding: 0px;
border: 1px solid blue;
}
View my full sample code on JSFiddle: https://jsfiddle.net/3t7vyebt/4/