为了练习和训练 CSS,我正在尝试做类似的事情:
换句话说,我正在尝试这样的事情:当我将鼠标悬停在第三段上时,第二段需要像图片一样获得颜色。
我正在尝试使用伪类 :hover
和 :before
(或 :after
)和 content
属性设置为 ""
,设置 background
为 #E7A51B
和 opacity
为 0.3
但它不起作用。
HTML 需要像这样:
<body>
<div class="app">
<p> First paragraph </p>
<div class="active">
<p> Second paragraph </p>
</div>
<br>
<div>
<p> Third paragraph </p>
</div>
</div>
</body>
编辑:感谢大家的评论。阅读您的评论,我想问是否有可能采用更通用的方法,例如:
如果我将鼠标悬停在 class="foo1"
背景元素上 class="foo2"
元素会发生变化吗?
最佳答案
当前 CSS (Selectors Level 3)
不幸的是,对于当前的 CSS 标准,您所尝试的是不可能的。但是,目前有什么可能呢?
给定以下标记:
<div class="app">
<p> First paragraph </p>
<p> Second paragraph </p>
<p> Third paragraph </p>
</div>
您可以定位同一级别(同一父级)上的元素并跟随您与之交互的初始元素(例如 :hover
)。 → Demo
/* targeting the direct descending sibling of the 3rd paragraph*/
p:nth-of-type(3):hover + p{
color:red;
}
/* targets the 4th paragraph when hovering the second */
p:nth-of-type(2):hover ~ p:nth-of-type(4){
color:blue;
}
/* targets all paragraphs being siblings of the first paragraph */
p:first-of-type:hover ~ p{
color:green;
}
future (Selectors Level 4)
Selectors Level 4 将(很可能)带来两个令人兴奋的新功能,它们可以实现您实际尝试做的事情:
1) - 我称之为 - subject indicator
- 它让您确定要定位复合选择器的哪个元素。
!OL > LI:only-child
将以只有一个列表元素的所有有序列表为目标(看起来很简单,但在当前的 css 下是不可能的)。
2) reference combinator
:
label:hover /for/ input
将以输入元素为目标,当通过它的 for
属性引用它的标签悬停时。
目前这还没有被任何浏览器支持,但是你看,我们可以为在不久的将来等待我们的 css 感到兴奋;)
关于html - CSS 将鼠标悬停在一个段落上,更改上一个段落的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17393905/