Element Alignment Shifts on Hover Due to Bold Styling
When implementing a horizontal menu using HTML lists and CSS, it's common to encounter a shift in the alignment of menu items when the hover state is applied. This shift occurs because the bold font size in the hover state differs from the standard font size.
This issue is similar to one discussed in a SitePoint post, but without a clear solution. Setting the width of the li items may not be feasible if the text width varies.
Solving the Alignment Shift
A solution lies in using an invisible pseudo-element to pre-set the width of the element. This pseudo-element mirrors the content and styling of the hover state, effectively defining the element's width before the hover state is triggered.
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; } /* SOLUTION */ /* The pseudo element has the same content and hover style, so it pre-sets the width of the element and visibility: hidden hides the pseudo element from actual view. */ a::before { display: block; content: attr(title); font-weight: bold; height: 0; overflow: hidden; visibility: hidden; }
In this solution:
By pre-setting the width, the menu items maintain their alignment on hover, regardless of the text length or width variation.
The above is the detailed content of Why Does My Horizontal Menu Shift on Hover, and How Can I Fix It Using Pseudo-elements?. For more information, please follow other related articles on the PHP Chinese website!