Solution to element movement caused by hover generated border

Time:2020-1-11

Preface

Sometimes we meethoverWhen a pseudo class adds a border to an element, the contents of the element are shifted, although we set thebox-sizing: border-boxThe width and height of the element are specified, but the content is still squeezed by the frame. As follows:


<style type="text/css" media="screen">
    .test {
        height: 30vmin;
        width: 30vmin;
        background: lightblue;
        box-sizing: border-box;
    }
    .test:hover {
        border: 5px solid black;
    }
</style>
<div class="test">
    this is a div.
</div>

The reason for this is obvious. Our element size does not change (if we do not set the element width and height orbox-sizing: border-boxThe element size will change),box-sizing: border-boxIt works, but the contents of the element are squeezed because of the suddenly added border. Our box model ismarginborderpaddingcontent, so newborderWill certainlycontentCompression is smaller, andcontentThe boundary coordinates of are also changed because of the visual content movement. So the way to solve the problem is to make the addition of borders not affectcontentLocation.

Add border to element

The unexpected border has changed the original layout and moved the content. In this case, we can make the border exist in the previous layout.


.test {
    height: 30vmin;
    width: 30vmin;
    background: lightblue;
    border: 5px solid transparent;
    box-sizing: border-box;
}
.test:hover {
    border: 5px solid black;
}

Using box shadow

Using thebox-shadowperhapsoutlineIt’s also a choice,


.test:hover {
    /* border: 5px solid black; */
    box-shadow: 0 0 0 5px black;
    outline: 5px solid black;
}

Using padding

We can changepaddingSize to giveborderReserve space.


.test {
    height: 30vmin;
    width: 30vmin;
    background: lightblue;
    box-sizing: border-box;
    padding: 5px;
}
.test:hover {
    padding: 0;
    border: 5px solid black;
}

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.