【发布时间】:2021-08-08 06:37:41
【问题描述】:
挑战:
- 当悬停列表的
<li>元素时,名为li:last-child:after的伪元素会受到影响 - 根据
<li>得到:hovered,伪元素会受到影响
例子:
- 悬停
li:nth-child(1)应将伪元素100px向右移动, - 悬停
li:nth-child(2)应将伪元素200 px向右移动,等等。
编码:
对于<li> 1 到 3 的项目,我成功完成了这项工作,但不幸的是,最后一个孩子没有。我的问题在哪里?
ul {
display: flex;
width: max-content;
list-style: none;
padding: 0;
margin: 0 auto;
}
a {
display: block;
width: 100px; height: 50px;
color: white;
background-color: orange;
}
/*Creating the pseudo element */
li:last-child:after {
content: '';
position: absolute;
top: 100px; left: 100px;
width: 50px; height: 50px;
background-color: red;
transition: transform 1s;
}
/*Creating the desired action for li childs 1 to 3*/
li:nth-child(1):hover ~ li:last-child:after { transform: translatex(100px);}
li:nth-child(2):hover ~ li:last-child:after { transform: translatex(200px);}
li:nth-child(3):hover ~ li:last-child:after { transform: translatex(300px);}
/*Failed experiments about creating the desired action for li last child*/
li:nth-child(4):hover + li:last-child:after { transform: translatex(400px);}
li:nth-child(4):hover ~ li:last-child:after { transform: translatex(400px);}
li:nth-child(4):hover > li:last-child:after { transform: translatex(400px);}
li:nth-child(4):hover li:last-child:after { transform: translatex(400px);}
<div>
<ul>
<li><a href="#">Test 1</a></li>
<li><a href="#">Test 2</a></li>
<li><a href="#">Test 3</a></li>
<li><a href="#">Test 4</a></li>
</ul>
</div>
【问题讨论】:
-
因为第 4 个元素是最后一个子元素
-
您有什么理由不能创建一个空的
<li>作为您的最后一个孩子并将其用作您的红块?摆脱 after 伪并将空 li 定位为最后一个孩子。
标签: html css flexbox css-selectors pseudo-element