Inline elements shifting when made bold on hover

Billy picture Billy · Feb 17, 2009 · Viewed 174.9k times · Source

I created a horizontal menu using a HTML lists and CSS. Everything works as it should except when you hover over the links. You see, I created a bold hover state for the links, and now the menu links shift because of the bold size difference.

I encounter the same problem as this SitePoint post. However, the post does not have proper solution. I've searched everywhere for a solution and can't find one. Surely I can't be the only one trying to do this.

Does anyone have any ideas?

P.S: I don't know the width of the text in menu items so I cannot just set the width of the li items.

Answer

350D picture 350D · Nov 27, 2013

li {
    display: inline-block;
    font-size: 0;
}
li a {
    display:inline-block;
    text-align:center;
    font: normal 16px Arial;
    text-transform: uppercase;
}
a:hover {
    font-weight:bold;
}
a::before {
    display: block;
    content: attr(title);
    font-weight: bold;
    height: 0;
    overflow: hidden;
    visibility: hidden;
}
<ul>
    <li><a href="#" title="height">height</a></li>
    <li><a href="#" title="icon">icon</a></li>
    <li><a href="#" title="left">left</a></li>
    <li><a href="#" title="letter-spacing">letter-spacing</a></li>
    <li><a href="#" title="line-height">line-height</a></li>
</ul>

Check the working example on JSfiddle. The idea is to reserve space for bolded (or any :hover state styles) content in :before pseudo element and using title tag as a source for content.