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?
Just decrease the width and height by double of border-width
You can try a box-shadow inset
something like this: box-shadow:inset 0px -5px 0px 0px #fff
adds a white 5px border to the bottom of the element without increasing the size
In case content of your div
is rendered dynamically and you want to set its height, you can use a simple trick with outline
:
button {
padding: 10px;
border: 4px solid blue;
border-radius: 4px;
outline: 2px solid white;
outline-offset: -4px;
}
button:hover {
outline-color: transparent;
}
Example here: https://codepen.io/Happysk/pen/zeQzaZ
The border css property will increase all elements "outer" size, excepts tds in tables. You can get a visual idea of how this works in Firebug (discontinued), under the html->layout tab.
Just as an example, a div with a width and height of 10px and a border of 1px, will have an outer width and height of 12px.
For your case, to make it appear like the border is on the "inside" of the div, in your selected CSS class, you can reduce the width and height of the element by double your border size, or you can do the same for the elements padding.
Eg:
div.navitem
{
width: 15px;
height: 15px;
/* padding: 5px; */
}
div.navitem .selected
{
border: 1px solid;
width: 13px;
height: 13px;
/* padding: 4px */
}
This is also helpful in this scenario. it allows you to set borders without changing div width
textarea {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}
Taken from http://css-tricks.com/box-sizing/
Another good solution is to use outline
instead of border
. It adds a border without affecting the box model. This works on IE8+, Chrome, Firefox, Opera, Safari.
(https://stackoverflow.com/a/8319190/2105930)