nazmul_94_hasan
nazmul_94_hasan

Reputation: 29

How to display an hidden div on an image with low opacity

Suppose I have an image. I want to display an div on the image with same width and same height of the image when I put the cursor on the image. Background of the div will be black included with opacity .6. AT first Below I included an code, but it is not working.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
.under_menu{
  width: 400px;
  height: 400px;
  background-color: black;
  opacity: .5;
  position: absolute;
  display: none;
}
.image:hover .under_menu{
  display: block;
  margin-top: -20px;
}
.main_menu{
  position: relative;
  display: inline-block;
}

</style>
  </head>`
  <body>
     <div class="main_menu">
       <img src="com22.jpg" class="image" width="400" height="400" alt="" />
       <div class="under_menu"></div>
     </div>
  </body>
</html>

Upvotes: 0

Views: 55

Answers (2)

Asons
Asons

Reputation: 87191

Give top: 0; left: 0; pointer-events: none to .under_menu and change .image:hover .under_menu to .image:hover ~ .under_menu and it will work fine.

The ~ is the sibling selector, which is needed, as .under_menu is not a child of the .image, and the pointer-events: none make it not flicker, as it takes away pointer events from the .under_menu.

This could be done using pseudo element as well, showed in my 2:nd sample.

.under_menu{
  top: 0;
  left: 0;
  width: 300px;
  height: 300px;
  background-color: black;
  opacity: .5;
  position: absolute;
  display: none;
  pointer-events: none;
}
.image:hover ~ .under_menu{
  display: block;
}
.main_menu{
  position: relative;
  display: inline-block;
}
<div class="main_menu">
  <img src="http://lorempixel.com/400/400/city" class="image" width="300" height="300" alt="" />
  <div class="under_menu"></div>
</div>

2:nd sample (using pseudo element)

.main_menu {
  position: relative;
  display: inline-block;
}
.main_menu:hover::after {
  content: '';
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: black;
  opacity: .5;
  position: absolute;
}
<div class="main_menu">
  <img src="http://lorempixel.com/400/400/city" class="image" width="300" height="300" alt="" />
</div>

Upvotes: 2

jerrylow
jerrylow

Reputation: 2629

The issue is that .image:hover .under_menu will never work because this is telling the CSS that one hover of .image its "child" .under_menu should do something but .under_menu is not a child its a sibling so you have to do .image:hover + .under_menu.

Or if you don't have any other elements inside you can do .main_menu:hover .under_menu.

https://jsfiddle.net/up4oswLm/

Upvotes: 0

Related Questions