Inline elements shifting when made bold on hover(悬停时加粗时内联元素移动)
问题描述
我使用 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="aGVpZ2h0">height</a></li>
<li><a href="#" title="aWNvbg==">icon</a></li>
<li><a href="#" title="bGVmdA==">left</a></li>
<li><a href="#" title="bGV0dGVyLXNwYWNpbmc=">letter-spacing</a></li>
<li><a href="#" title="bGluZS1oZWlnaHQ=">line-height</a></li>
</ul>
这篇关于悬停时加粗时内联元素移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:悬停时加粗时内联元素移动


- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01