我有一个 UI,长得像这样
+---------------------------+
| |
| +--area1--+ +--area2--+ |
| | | | | |
| | | | | |
| +---------+ +---------+ |
| |
+---------------------------+
我希望当鼠标悬停在区域1或区域2上时,两个区域都显示特定的样式。现在,如果指针悬停在区域1上,则会出现
+---------------------------+
| |
| +--area1--+ +--area2--+ |
| |.........| | | |
| |....☝....| | | |
| +---------+ +---------+ |
| |
+---------------------------+
如果指针在区域2上,我会得到
+---------------------------+
| |
| +--area1--+ +--area2--+ |
| | | |.........| |
| | | |....☝....| |
| +---------+ +---------+ |
| |
+---------------------------+
我希望的是,当指针悬停在区域1或区域2上时,这两个区域都显示其悬停状态。
+---------------------------+
| |
| +--area1--+ +--area2--+ |
| |.........| |.........| |
| |....☝....| |.........| |
| +---------+ +---------+ |
| |
+---------------------------+
只用CSS是否可以实现这个效果?
下面是一些HTML/CSS代码示例
* {
box-sizing: border-box;
}
html,body {
width: 100%;
height: 100%;
margin: 0;
}
.container {
display: flex;
justify-content: center;
align-content: center;
height: 100%;
}
.unrelatedcontainer {
width: 100%;
height: 100%;
border: 1px solid red;
}
.area1,
.area2 {
margin: 3em;
height: 80%;
border: 1px solid black;
display: flex;
justify-content: center;
align-content: center;
align-items: center;
}
.area1:hover,
.area2:hover {
background-color: green;
}
<div class="container">
<div class="unrelatedcontainer">
<div class="area1">
<div class="content">area1</div>
</div>
</div>
<div class="unrelatedcontainer">
<div class="area2">
<div class="content">area2</div>
</div>
</div>
</div>
.area1
和.area2
是并排的,那么你可以这样做。在你现有的标记中,唯一的解决方案是使用JavaScript(CSS无法定位父元素并返回找到第二个区域进行绘制)。 - Marcos Pérez Gude.unrelatedcontainer
,那么sibling selector
可能对你有所帮助。然而,仅使用CSS无法选择前一个兄弟元素:https://dev59.com/vnI-5IYBdhLWcg3whImk - Kyle O