Could we help you? Please click the banners. We are young and desperately need the money
One common issue when designing navigation menus is the unintended "shift" of menu items caused by font weight changes on hover. This blog post will guide you through solving this problem using a clean and efficient CSS approach. By the end, your menus will have a smooth hover effect without disrupting the layout.
When a font's weight changes, its dimensions may adjust slightly. This can lead to elements shifting, especially in inline or flex-based layouts. These layout disruptions harm user experience and can make your design feel unpolished.
To avoid layout shifts, we can use a clever CSS trick. The idea is to simulate the heavier font weight in a hidden pseudo-element, ensuring the layout remains stable when the font weight of the actual text changes on hover.
<nav id="main-menu">
<ul>
<li><a href="#" data-text="Home">Home</a></li>
<li><a href="#" data-text="About">About</a></li>
<li><a href="#" data-text="Services">Services</a></li>
<li><a href="#" data-text="Contact">Contact</a></li>
</ul>
</nav>
Here’s the full CSS code that implements the solution:
#main-menu > li > a {
display: inline-flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 7px 0;
color: var(--color-main);
transition: font-weight 0.1s ease;
}
#main-menu > li > a:after {
content: attr(data-text);
height: 0;
visibility: hidden;
overflow: hidden;
user-select: none;
pointer-events: none;
font-weight: bold;
}
#main-menu > li > a:is(:hover, :focus) {
font-weight: var(--font-bold);
}
This method is particularly useful in:
By using this CSS technique, you can create polished and user-friendly navigation menus that deliver a superior experience. Try implementing this in your next project and enjoy the benefits of smooth, accessible designs without layout disruptions!