Paweł Skaba Paweł Skaba - 4 months ago 64
HTML Question

Show element on hover another using css

I'm working on a tiny css action which based on A element hover, will display another element. The code is pretty basic:

<a title="#" class="portfolio-reaction" href="#">
<img src="http://i.imgur.com/OZb7SI8.png" class="attachment-grid-feat" />
<div class="headline-overlay">LOREM IPSUM</div>
</a>

.portfolio-reaction {
width:250px;
height:250px;
display:block;
}

.headline-overlay {
background:none;
height:100%;
width:100%;
display:none;
position:absolute;
top:10%;
z-index:999;
text-align:left;
padding-left:0.5em;
font-weight:bold;
font-size:1.3em;
color:#000;
}
.attachment-grid-feat:hover ~ .headline-overlay {
display:block;
}


and jsfiddle: https://jsfiddle.net/yL231zsk/1/

This solution works in 99%. The missing percent is the effect - while moving mouse arrow through the button, text is blinking. I have no idea why. Secondly - what if I want to extend number of appearing elements from 1 to 3. So to have:

<a title="#" class="portfolio-reaction" href="#">
<img src="http://i.imgur.com/OZb7SI8.png" class="attachment-grid-feat" />
<div class="headline-overlay">
<p class="element-1">abc</p>
<p class="element-2">111</p>
<div class="element-3">X</div>
</div>
</a>


Thank you for any tips and advices.

Answer

You wrote the following in your css file :

.attachment-grid-feat:hover ~ .headline-overlay {
    display:block;
}

It won't work since .attachment-grid-feat isn't the parent of .headline-overlay. So it won't select the state when the parent is selected because there are no element .healine-overlay inside .attachment-grid-feat. Also no need to add ~ between the two. The right selector is the following :

.portfolio-reaction:hover .headline-overlay {
    display: block;
}

This way you are targeting the child div .healine-overlay when parent div .portfolio-reaction (you might want to make the a tag a div tag) is hovered.

.portfolio-reaction {
  width:250px;
  height:250px;
  display:block;
}

.headline-overlay {
	background:none;
	height:100%;
	width:100%;
	display:none;
	position:absolute;
	top:10%;
	z-index:999;
	text-align:left;
	padding-left:0.5em;
	font-weight:bold;
	font-size:1.3em;
	color:#000;
}
.portfolio-reaction:hover .headline-overlay {
	display: block;
}
<div title="#" class="portfolio-reaction" href="#">
  <img src="http://i.imgur.com/OZb7SI8.png" class="attachment-grid-feat" />
  <div class="headline-overlay">
    <div id="element-1">Hello 1</div>
    <div id="element-2">Hello 2</div>
    <div id="element-3">Hello 3</div>
  </div>
</div>

By the way, in this code snippet, three elements are contained inside .headline-overlay. On hover, all three elements are displayed.