Inline Elements Shifting on Hover Due to Bold Styling
Many developers encounter the issue of inline elements shifting when bold font is applied on hover. Lists, for example, may present this problem when list items have dynamic text content.
In the example provided, a horizontal menu is created using HTML lists and CSS, and hover styling is applied to bolden the links. However, the menu items shift during hover due to the change in element width caused by bold font.
Solution Using Pseudo-Elements
To address this issue, a clever solution involves using an invisible pseudo-element to pre-set the width of the element. The content of this pseudo-element matches that of the parent element, and hover styling is applied to it. By hiding this pseudo-element visually, we effectively pre-set the width for the parent element before applying bold hover styling.
Here's the modified CSS code:
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; }
By adding the pseudo-element and the corresponding hover style, the width of the element is pre-set before bold styling is applied. As a result, the menu items will no longer shift during hover.
Usage and Considerations
The value of the title attribute for each link should match its expected hovered text. This ensures that the pseudo-element pre-sets the width correctly for each link.
It's important to note that this solution works specifically for inline elements that have dynamic text content. For more complex elements or scenarios, alternative approaches may be required.
The above is the detailed content of Why Do Inline Elements Shift on Hover When Bold Font is Applied, and How Can Pseudo-Elements Solve This?. For more information, please follow other related articles on the PHP Chinese website!