DEV Community

Rae Liu
Rae Liu

Posted on

How to fix elements shifting issue in bold on hover

Using &:hover{ font-weight: bold } is a common sense to a FE developer. But the font shifts to right when we use bold. Sometimes it can cause line break or layout issue.

Here are two css-only solutions:

1 text-shadow

text-shadow: 0 0 1px black;
text-shadow: 0 0 1px black, 0 0 1px black; //bolder
Enter fullscreen mode Exit fullscreen mode
  1. value = The X-coordinate
  2. value = The Y-coordinate
  3. value = The blur radius
  4. value = The color of the shadow

As an alternative solution for bold, the first and the second value can be set to 0.

Note
Safari doesn't support decimal number, which means it has to be 1px.
Firefox is very sensitive with blur radius, and 1px is too much

2 text-stroke

text-stroke: 1px black;
-webkit-text-stroke: 1px black; //Firefox and Edge
Enter fullscreen mode Exit fullscreen mode

Note
IE doesn't support text-stoke

3 Conclusion

text-stroke

It seems to be a best solution without IE. Here is a best solution I can find to include IE.
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) can detect IE hover.

@mixin m-hover-ie {
  @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
     @content;
  }
 a:hover{
        text-stroke: 1px black;
        -webkit-text-stroke: 1px black;
    }
     @include m-hover-ie{
       &:hover{
        text-shadow: 0 0 1px black; 
       }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

text-shadow

If you really want to use text-shadow in IE...
-moz-touch-enabled can detect Firefox hover. But this is not a standard feature, and won't work for every user.
In my personal experience, it works on Firefox v60 and above.

@mixin m-hover-firefox {
    @media (-moz-touch-enabled: 0){
        @content;
    }
}
a:hover{
      text-shadow: 0 0 1px;
      @include m-hover-firefox{
        text-shadow: 0 0 .2px;
      }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
sushantktiwari profile image
SushantKTiwari

Hi Rae,

There is a another very basic solution for this..

Step1: just take the text in span
a href="#">This is only a hot fix</a

a href="#">
span>This is only a hot fix /span>
/a>

Step2: Copy it to two times:
a href="#">
span>This is only a hot fix span>This is only a hot fix /a>

Step3: 1st should have Visibility:hidden, and 2nd have position: absolute.

a href="#" style="position:relative">
span style="visibility:hidden;white-space:nowrap">This is only a hot fix span class="hover-item" style="position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);white-space: nowrap;">This is only a hot fix</span
</a

a:hover .hover-item{font-weight:bold}

Thanks & Regards

Collapse
 
persimone profile image
Simone

Big help! Thank you!!!

Collapse
 
philw_ profile image
Phil Wolstenholme

css-tricks.com/bold-on-hover-witho... is my favourite technique for doing this