如何使用具有悬停效果的选择器

时间:2016-10-05 20:12:07

标签: html css css-selectors hover

我试图这样做,当某个图像悬停时,会显示某些文字!

所以我想说我有这个HTML:

<div class="container">
  <div class="pic1">
    <img src="linkToThePicture" class="imag">
    <p>this should appear when the pic1 div is hovered</p>
  </div>
  <div class="pic2">
    <img src="linkToThePicture2" class="imag">
    <p>this should appear when the pic2 div is hovered</p>
  </div>
</div>

让我说我也有这个CSS:

div {
height: 150px;
width: 150px;
/*makes all the picture containers same size*/
float: left;
display: inline;
/*makes all the pictures come one after another in a row*/
}

p {
opacity: 0;
/*do this so that all the p's are invisible at first*/
}

.container {
height: 1000px;
width: 1000px;
/*arbitrary settings for height and width of the container, if i am correct, this will override the above mentioned div settings*/
}

.imag {
width: 150px;
height: 150px;
/*makes all pics same size*/
}

/*now i would need something here to make it so when pic1 is hovered, it p element would change to have "opacity: 1;". My original thought would be this:*/
.div1:hover .div1 < p {
opacity: 1 !important;
/*but that didnt work!*/
}

所以有人知道这样做的正确方法吗?谢谢!

2 个答案:

答案 0 :(得分:0)

最简单的解决方案是将.div1:hover .div1 < p {更改为.pic1:hover p

由于以下几个原因,您的代码无效:

  1. 班级“div1”
  2. 没有任何内容
  3. <在CSS选择器中没有任何意义
  4. .pic1:hover p表示“正在悬停的类p的元素中的任何pic1。”

    如果您想再清理一下代码,可以像这样定义一个pic类,并将其添加到div个:{/ p>

    .pic {
      height: 150px;
      width: 150px;
    }
    

    这样,您就不需要重置容器元素的大小。然后,添加此声明,它将适用于div s:

    .pic:hover p {
        opacity: 1;
    }
    

答案 1 :(得分:0)

你应该能够使用兄弟选择器,因为它们在标记中直接相邻:

.container .imag:hover+p {
    opacity: 1;
}