Home >Web Front-end >CSS Tutorial >How to Prevent Inline Element Horizontal Shift on Hover When Bolding?

How to Prevent Inline Element Horizontal Shift on Hover When Bolding?

Barbara Streisand
Barbara StreisandOriginal
2025-01-04 04:33:41275browse

How to Prevent Inline Element Horizontal Shift on Hover When Bolding?

Solve the problem of offset after inline elements become thicker when hovering

When using HTML lists and CSS to create horizontal menus, users may You will encounter a problem: when you set the link to be thicker and thicker when suspended, the menu link will be offset due to the difference in thickness.

To solve this problem we can adopt the following solution:

Preset the width

Use an invisible pseudo-element that has Same content and style as parent hover style. Use data attributes (such as title) as the source of content.

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;
}
<ul>
  <li><a href="#" title="height">height</a></li>
  <li><a href="#" title="icon">icon</a></li>
  <li><a href="#" title="left">left</a></li>
  <li><a href="#" title="letter-spacing">letter-spacing</a></li>
  <li><a href="#" title="line-height">line-height</a></li>
</ul>

The above is the detailed content of How to Prevent Inline Element Horizontal Shift on Hover When Bolding?. 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
Previous article:winter solstice websiteNext article:winter solstice website