Home >Web Front-end >CSS Tutorial >How Can I Prevent Horizontal Menu Items from Shifting When Text Becomes Bold on Hover?

How Can I Prevent Horizontal Menu Items from Shifting When Text Becomes Bold on Hover?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-28 15:44:21218browse

How Can I Prevent Horizontal Menu Items from Shifting When Text Becomes Bold on Hover?

Inline Elements Shifting When Made Bold on Hover

When elements within a horizontal menu shift upon hovering, it can be attributed to the variation in size between regular and bold text. This article explores the solution to this common problem.

Understanding the Issue

In the example provided, HTML lists and CSS are used to create a horizontal menu. When hovering over links, the text becomes bold, causing the links to shift because of the difference in width between regular and bolded text.

Pre-set the Width

The solution involves pre-setting the width of the elements using an invisible pseudo-element. This pseudo-element contains the same content and styling as the parent's hover state.

a::before {
    display: block;
    content: attr(title);
    font-weight: bold;
    height: 0;
    overflow: hidden;
    visibility: hidden;
}
  • Display: block: Makes the pseudo-element occupy the full width of its container.
  • Content: attr(title): Fetches the content from the parent's title attribute, allowing it to share the same text.
  • Font-weight: bold: Applies the bold styling to the pseudo-element.
  • Height: 0; Overflow: hidden; Visibility: hidden: Hides the pseudo-element from view, ensuring it doesn't affect the element's overall appearance.

By using a pseudo-element with these properties, the width of the element is pre-set even before the hover state is applied, eliminating the shifting issue.

The above is the detailed content of How Can I Prevent Horizontal Menu Items from Shifting When Text Becomes Bold on Hover?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn