简体   繁体   中英

Show child element on parent hover in CSS

Is it possible to toggle the Delete button when mouse hovers onto the parent div in pure CSS?

HTML

<div id="parent">
    <button class="hidden-child">delete</button>
</div>

CSS

#parent:hover{
    /* Some CSS here */
}

if you have styled hide like this (the page will be displayed as if the element is there but not seen):

#parent .hidden-child{
    visibility: hidden;
}

you may do it like this to just hide it:

#parent:hover .hidden-child{
    visibility: visible;
}

and if you have styled it like this (the page will be displayed as if the element is not there):

#parent .hidden-child{
    display: none;
}

you may do it like this:

#parent:hover .hidden-child{
    display: block;
}

In Action!

 #parent { width: 10rem; height: 10rem; background-color: #ababab; } #parent.hidden-child{ visibility: hidden; } #parent:hover.hidden-child{ visibility: visible; }
 <div id="parent"> <button class="hidden-child">Delete</button> </div>

Without knowing how you've styled your controls,if you are using any css-js related libraries, the class ".hide" is most likely defined there and will be called by default which will then hide your button thus you manipulate it using JQuery or Javascript.

However, if you have vanillarised your code and the hidden state of your button is display:none; users will be left with a blank page not knowing what or where to hover so you must give them something to hover on:

Sol 1:

HTML:
<div id="something">
     Hover Here
    <button class="hides">delete</button>
</div>

CSS:
#something .hides{

    display:none;
}

#something:hover .hides{

    display:inline-block;
}

If the hidden state of your button is visibility:hidden ;this will hide the button but will still reserve its space on the screen thus leaving an awkward interface unless you make it fancy with styling.

Sol 2:

HTML:

<div id="something">
    <button class="hides">delete</button>
</div>

CSS:
#something{

    /*My fancy style;*/
}
#something .hides{

    visibility: hidden;
}

#something:hover .hides{

        visibility: visible;
}

There are two states in your situation, the first one is when the mouse hover the element the second is when it doesn't as a result leave

here you have to target the element .hide when the pointer is on div then then disable any click event that may occur.

code snippet:

div#something:hover .hide{

   pointer-events: none;
   color: GrayText;
   background-color: #ddd;
   background: #ddd;
}

working example:

jsfiddle

cheers

to hide element initially


#something > .hide {
  display: none;
}

display element on hover

#something:hover {
  .hide {
    display: inline;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM