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="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>
这篇关于悬停时加粗时内联元素移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:悬停时加粗时内联元素移动
基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01