[英]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>
.我试图在将鼠标悬停在
<ul>
内的<ul>
<li>
元素上时创建叠加效果。
I want this element to be common to every <li>
.我希望这个元素对每个
<li>
都是通用的。
My first idea was to put an additional element, like a <div>
, inside the list.我的第一个想法是在列表中添加一个额外的元素,例如
<div>
。
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.但是,除了
<li>
之外,我们不能在<ul>
放置任何标签,因为它会被视为无效标记。
Since there is no way to select the parent of an element, is there any way to resolve this issue using CSS only?由于无法选择元素的父元素,有没有办法仅使用 CSS 来解决此问题?
You can use :before
and :after
pseudo elements if your needs are simple.如果您的需求很简单,您可以使用
:before
和:after
伪元素。
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?如果您尝试使用子元素来选择父元素,目前这是不可能的: 是否有 CSS 父选择器?
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.您可以在
:hover
伪类上使用背景颜色。 You can also use :before
and/or :after
as well.您也可以使用
:before
和/或:after
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.