实际效果: https://codepen.io/clarence-sampson/pen/poQMjvb
demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>direction-aware effects</title>
<style>
* {
font-family: system-ui;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
html,
body {
height: 100%;
}
body {
font-family: system-ui;
font-size: 2.25rem;
}
nav ul {
list-style: none;
display: flex;
--item-gap: 2rem;
}
nav a {
color: inherit;
opacity: 0.7;
text-decoration: none;
text-transform: uppercase;
font-weight: 500;
}
nav li {
position: relative;
overflow: hidden;
padding: calc(var(--item-gap) / 2);
/* min-inline-size: 3rem; */
}
nav a:hover,
nav a:focus-visible {
opacity: 1;
color: #B70075;
}
nav li::after {
content: "";
position: absolute;
background-color: orangered;
/* bottom: -2rem; */
/* left: 0; */
bottom: 0;
height: 3px;
width: 100%;
}
</style>
</head>
<body>
<nav>
<ul>
<li><a href="">Home</a></li>
<li><a href="">Blog</a></li>
<li><a href="">About</a></li>
<li><a href="">Contact me</a></li>
</ul>
</nav>
</body>
</html>
问题
- 为什么background-color没有全部生效,是因为脱离文档流候被覆盖了吗?
- 红色箭头指的这两个数字是什么?
两个问题都是因为你给
::after
伪类元素指定了position:absolute
绝对定位导致的。设置完
position:absolute
之后如果没有指定定位信息,就出现会在元素原本的位置并移出文档流。所以你选中::after
伪类之后,页面中高亮提示的部分就会超出li
元素(overflow: hidden
)的可见范围。指定::after
伪类的left
值为0
就可以解决问题了。第二个问题的定位信息,就是
::after
伪类定位方式修改为绝对定位后元素的定位信息。至于为什么不设置绝对定位时看不到这些数值,是因为非定位元素的left
、top
、right
、bottom
四个定位属性是无效的,所以也不会展示在DevTools
的 盒模型 视图中。