如何在兄弟姐妹的悬停中显示元素?

时间:2017-09-04 16:37:25

标签: html css css-selectors

我一直在测试CSS选择器。当我将p悬停时,我想更改h3的显示,所以我写了类似的内容:

div > p{
    display: none;
}

div > h3:hover p{
    display: block;
}
<div>
    <h3>Lorem ipsum dolor sit amet</h3>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>

但它不起作用。这有什么不对?我错过了什么?

2 个答案:

答案 0 :(得分:8)

使用+ adjacent sibling selector

div > p {
  display: none;
}

div > h3:hover + p {
  display: block;
}
<div>
  <h3>HOVER ME</h3>
  <p>Lorem ipsum dolor sit amet...</p>
</div>

回顾
h3 p ...表示ph3的后代 h3 + p ...意味着ph3

的直接下一个兄弟

如果您计划在不久的将来在h3p之间使用其他元素而不是General sibling selector ~,那么

div > p {
  display: none;
}
div > h3:hover ~ p {    /* notice the general sibling selector */
  display: block;
}

.line{background: red; height: 1px; }
<div>
  <h3>HOVER ME</h3>
  <div class="line"></div>
  <p>Lorem ipsum dolor sit amet...</p>
</div>

答案 1 :(得分:3)

您可以使用相邻的兄弟选择器+),例如div > h3:hover + p

见下面的演示:

div>p {
  display: none;
}

div>h3:hover+p {
  display: block;
}
<div>
  <h3>Lorem ipsum dolor sit amet</h3>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>