Increase border width on hover without moving other content

In this post, I describe how to increase the border thickness when you hover over an element without causing other elements on the page to move around.


Cause

If you add or increase the border width (top or bottom) of an element, it will increase the height of that element, which can cause other things on the page to move down.


Resolution

Element does not have a border

If your element doesn't already have a border, you can add a transparent border, then change this to a coloured border on hover, for example:

.item { border: 1px solid transparent; }
    .item:hover { border-color: red; }
Screenshot showing an element and its hover state when the element does not already have a border

Element has a border

There are three ways to add a thicker border on hover if the element already has a border:

1. Reserve space in the element and expand the thicker border into that space.  For example, if you have an a element sized using line-height, you can set the min-height to a slightly bigger value to cater for the thicker border on hover:

.item {

    line-height: 2rem;

    min-height: 2.27rem;

} 

    .item:hover {

        border-bottom-width: 2px;

    }

Screenshot showing an element and its hover state with space reserved in the element


2. Reserve space below the element and expand the thicker border into that space.  For example, add 1px of margin-bottom to your element.  Then, set margin-bottom to 0 and add 1px to the border-width on hover:

.item {

    margin-bottom: 1px;

} 

    .item:hover {

        margin-bottom: 0;

        border-bottom-width: 2px;

    }

Screenshot showing an element and its hover state with space reserved below the element

3. Don’t reserve any space and just expand the thicker border over the top of anything below.  For example, apply -1px of margin-bottom and add 1px to the border-width on hover:

.item:hover {

    margin-bottom: -1px;

    border-bottom-width: 2px;

}

Screenshot showing the thicker border on hover over the top of the content below

Or, apply a box-shadow with a colour that matches the border-color:

.item:hover {

    box-shadow: 0 2px #00599E;

}

Comments

Popular posts from this blog

LG TV This app will now restart to free up more memory

LG TV Clear All Browsing History Data

Excel Import CSV not using "Use First Row as Headers"