拆分幻灯片同级,悬停时一个同级会影响另一个同级



我正试图实现与Navy.com标题类似的效果,在Navy.com标头中,您将鼠标悬停在一个同级上,它会滑动以占据大部分空间,同时收缩和隐藏另一个同级的内容。

由于CSS标准不能选择以前的兄弟姐妹,我只能用一侧而不能用另一侧来实现效果。我知道单用CSS可能无法做到这一点。

提前感谢您的帮助!

这是我目前使用的代码:

.container {
display: flex;
flex-direction: row-reverse;
}
.b1 {
display: flex;
order: 2;
width: 50%;
height: 150px;
padding: 10px;
background-color: rgb(40, 251, 202);
transition: all 0.5s;
}
.b2 {
display: flex;
width: 50%;
order: 1;
height: 150px;
padding: 10px;
background-color: rgb(227, 29, 103);
transition: all 0.5s;
}
.b1:hover {
width: 80%;
}
.b2:hover {
width: 80%;
}
.b1:hover~.b2 {
background-color: rgba(227, 29, 103, 0.4);
width: 20%;
}
.b2:hover~.b1 {
background-color: rgba(40, 251, 202, 0.4);
width: 20%;
}
.b1:hover~.b2 span {
display: none;
}
.b2:hover~.b1 span {
display: none;
}
<div class="container">
<div class="b2">
<span>This content will show up directly in its container.</span>
</div>
<div class="b1">
<span>This content will show up directly in its container.</span>
</div>
</div>

只要进行一点重组,您就可以只使用CSS来达到您想要的效果。在这个实现中,我使用了:not CSS选择器,并结合了一些多级:hover选择器(这是因为.container.child占用相同的空间(

不过,作为一个建议:利用flex的自动增长,并完全删除width: 20%;逻辑。这样,未覆盖组件的子级将占据相等的空间,而悬停的子级仍将增长到80%的宽度。这将允许您动态添加更多项目,而无需更改硬编码的CSS。

.container {
display: flex;
}
.child {
width: 50%;
height: 150px;
padding: 10px;
transition: all 0.5s;
}
.child--red {
background-color: rgba(227, 29, 103, 1);
}
.container:hover .child--red:not(:hover) {
background-color: rgba(227, 29, 103, 0.4);
}
.child--green {
background-color: rgba(40, 251, 202, 1);
}
.container:hover .child--green:not(:hover) {
background-color: rgba(40, 251, 202, 0.4);
}
.container:hover .child:not(:hover) span {
display: none;
}
.container:hover .child {
width: 20%;
}
.container:hover .child:hover {
width: 80%;
}
<div class="container">
<div class="child child--green">
<span>This content will show up directly in its container.</span>
</div>
<div class="child child--red">
<span>This content will show up directly in its container.</span>
</div>
</div>

最新更新