2016-10-05 4 views
-1

特定の画像が表示されたときに、特定のテキストが表示されるようにしています。ホバー効果でセレクタを使用する方法

<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!*/ 
} 

だから、誰もがこれを行うには正しい方法を知っているん

はので、私はこのHTMLを持って言うことができますか?ありがとう!

+0

重複http://stackoverflow.com/questions/14263594/how-to-show-text-on-image-when-hovering – zaingz

答えて

0

最も簡単な解決策は.div1:hover .div1 < p {.pic1:hover pに変更することです。

あなたのコードは、カップルの理由のために動作しません。

  1. クラス「DIV1」とは何もありません
  2. <

.pic1:hover p手段」CSSセレクタでは意味がありませんどんなpであっても、クラスpic1を持っている要素の中にあるものです。

もう少しコードをクリーンアップしたい場合は、あなたがこのようpicクラスを定義して、両方のdiv秒にそれを追加することができます。

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

こうすることで、あなたがリセットする必要はありませんコンテナ要素のサイズ。その後、両方のdiv秒にこの宣言を追加し、それが適用されます:

.pic:hover p { 
    opacity: 1; 
} 
+0

私は何が間違っているのかを教えてくれてありがとう、なぜあなたが持っている方が良いか説明してください。また、コードクリーンアップのおかげで、常にそれを持っているように。 – skyleguy

0

彼らはマークアップに直接隣接しているので、あなたは、兄弟セレクタを使用して逃げることができる必要があります:の

.container .imag:hover+p { 
    opacity: 1; 
} 
関連する問題