Alexander Novikov Alexander Novikov - 4 months ago 6
HTML Question

Prevent text from shifting when hovered

I'm new to flexbox and trying to make a menu using it.

I want links to have a nice border on the bottom when user hovers on them. But even if I set

box-sizing: border-box;
flex keeps recalculating text position and element 'jumps' instead of predicted behaviour.

I have an example with the problem. I don't want content inside my element to jump when I hover.

Is there any simple solution/edition to my code to make it work as expected? I know other ways of achieving what I want: set baseline, use relative/absolute positioning...



.item {
display: flex;
width: 200px;
height: 100px;
background: #123;
color: #fff;
text-align: center;
justify-content: center;
flex-direction: column;
}
.item:hover {
border-bottom: 10px solid lightgreen;
box-sizing: border-box;
}

<div class="item">
Content
</div>




Answer

One method is to reserve the space for the border at all times.

This way the border space is factored in when the element is not hovered (and has the same background color). Then you simply change the border color on hover.

To keep the text centered, take the border out of the document flow with absolute positioning.

.item {
  display: flex;
  width: 200px;
  height: 100px;
  background: #123;
  color: #fff;
  text-align: center;
  justify-content: center;
  flex-direction: column;
  position: relative;
}
.item::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  border-bottom: 10px solid #123;
}
.item:hover::after {
  border-bottom: 10px solid green;
}
<div class="item">Content</div>