简体   繁体   中英

How to show the same element when hovering a li using only CSS?

I'm trying to create an overlay effect when hovering on a <li> element inside a <ul> .
I want this element to be common to every <li> .

My first idea was to put an additional element, like a <div> , inside the list.
Sketchy example:

<ul>
    <li></li>
    <li></li>
    <li></li>
    <div></div>
</ul>
ul div {
   opacity: 0
}
li:hover ~ div {
   opacity: 1
}

However, we can't put any tag inside a <ul> other than a <li> , because it would be considered invalid markup.

Since there is no way to select the parent of an element, is there any way to resolve this issue using CSS only?

You can use :before and :after pseudo elements if your needs are simple.

If you are trying to use a child element to select a parent element, that is not curently possible: Is there a CSS parent selector?

Minimal Example:

 li:hover:after{ display:inline-block; content:"pseudo element"; background-color:#ccc; }
 <ul> <li>aaa</li> <li>bbb</li> <li>ccc</li> </ul>

Extended example with some attribute defined text:

 ul li:hover:before, li:hover:after{ display:inline-block; position:absolute; float:right; content:attr(data-myMessage); animation-duration: 250ms; animation-name: slidein; margin-left: 0; background-color:#bada55; } li:hover:after{ animation-name: slideinleft; opacity:0%; margin-left: -1rem; } @keyframes slidein { from { margin-left: 10rem; opacity:0%; } to { margin-left: 0rem; opacity:100%; } } @keyframes slideinleft { from{ margin-left: -10rem; opacity:0%; } to { margin-left: -1rem; opacity:100%; } }
 <ul> <li data-myMessage="message">aaa</li> <li data-myMessage="something">bbb</li> <li data-myMessage="bottle">ccc</li> </ul>

You can use background color on :hover pseudo class. You can also use :before and/or :after as well.

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