Changing Border Width Without Moving Element

June 18, 2012 at 2:59 pm By

This is just a quick little tip I’ve came across that might be useful to you! Ever want to change the border of an item when you hover or click on it, but have to resort to position: relative;? Well do not fret, because there is a much simpler way to accomplish what you want!

You can use a transparent border, but this is no good if you want an initial border. So lets say you have an input with a 1px #eee border.

input {
    border: 1px solid #eee;
}

On hover you want this border to change to a 2px grey border. Of course, normally you would have to change the position of the element which can get a little messy. Instead, we’re going to use a box shadow!

input:hover {
    border: 1px solid #eee;	
    box-shadow: 0px 0px 0px 1px #eee;
}

And voila! We have a 2px border now. The box shadow value we changed was spread, so normally the box shadow would be invisible as it would be under the element, but since we increased spread by 1px we end up with 1px going over the side of the element. This acts as a pseudo-border. You could expand this to 3px or 4px by changing the ‘1px’ value in the box shadow to 2px for 3px, 3px for 4px, etc. Try clicking on this input to see how it works: