悬停时加粗时内联元素移动
我使用 HTML 列表和 CSS 创建了一个水平菜单.除非您将鼠标悬停在链接上,否则一切正常.你看,我为链接创建了一个粗体悬停状态,现在菜单链接由于粗体大小不同而发生了变化.
I created a horizontal menu using a HTML lists and CSS. Everything works as it should except when you hover over the links. You see, I created a bold hover state for the links, and now the menu links shift because of the bold size difference.
我遇到了与 此 SitePoint 帖子相同的问题.但是,该帖子没有适当的解决方案.我到处寻找解决方案,但找不到.当然,我不可能是唯一一个尝试这样做的人.
I encounter the same problem as this SitePoint post. However, the post does not have proper solution. I've searched everywhere for a solution and can't find one. Surely I can't be the only one trying to do this.
有人有什么想法吗?
P.S:我不知道菜单项中文本的宽度,所以我不能只设置 li 项的宽度.
P.S: I don't know the width of the text in menu items so I cannot just set the width of the li items.
.nav { margin: 0; padding: 0; }
.nav li {
list-style: none;
display: inline;
border-left: #ffffff 1px solid;
}
.nav li a:link, .nav li a:visited {
text-decoration: none;
color: #000;
margin-left: 8px;
margin-right: 5px;
}
.nav li a:hover{
text-decoration: none;
font-weight: bold;
}
.nav li.first { border: none; }
<ul class="nav">
<li class="first"><a href="#">item 0</a></li>
<li><a href="#">item 1</a></li>
<li><a href="#">item 2</a></li>
<li><a href="#">item 3</a></li>
<li><a href="#">item 4</a></li>
</ul>
推荐答案
预设宽度,使用一个不可见的伪元素,其内容和样式与父悬停样式相同.使用数据属性,如 title
,作为内容的来源.
Pre-set the width by using an invisible pseudo-element which has the same content and styling as the parent hover style. Use a data attribute, like title
, as the source for 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>
相关文章