Home > Web Front-end > CSS Tutorial > Why Does My Horizontal Menu Shift on Hover, and How Can I Fix It Using Pseudo-elements?

Why Does My Horizontal Menu Shift on Hover, and How Can I Fix It Using Pseudo-elements?

Mary-Kate Olsen
Release: 2024-12-23 18:06:11
Original
475 people have browsed it

Why Does My Horizontal Menu Shift on Hover, and How Can I Fix It Using Pseudo-elements?

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;
}
Copy after login

In this solution:

  • The pseudo-element (::before) is defined with block display, allowing it to pre-set the width of the element.
  • It inherits the content and font-weight from the hover state (using attr(title) to set the content).
  • The pseudo-element's height and overflow are set to 0 and hidden, respectively, to hide it from view.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template