删除子元素上的CSS过滤器

时间:2018-07-03 12:03:49

标签: css

我的CSS代码有问题。

如您所见,我在li元素上有过滤器,但它覆盖了其他元素。我需要使其他两个元素都没有过滤器:

有可能这样做吗?

.main {
  width:300px;
  height:300px;
  background-color:blue;
  list-style:none;
}

.button {
    position: absolute;
    top: 35% ;
    height: 30px;
    width: 120px;
    display: none;
    z-index: 99;
    background-color:black;
    color:white;
}

.icon {
    width: 30px;
    position: absolute;
    z-index: 99;
    display: none;
    width:100px;
}

.main:hover > .button {
    display: block;
    filter: none;
}

.main:hover > .icon {
    display: block;
    filter: none;
}

.main:hover {
    filter: brightness(50%);
    transition: 0.5s;
}
<li class="main">
<img src="https://help.seesaw.me/hc/en-us/article_attachments/204081043/bear.png" class="icon" />
<a class="button" href="#">Button</a>
</li>

2 个答案:

答案 0 :(得分:2)

您不能那样做。孩子会受到父母风格的影响。
这就是层叠样式表的工作方式。

我建议您使用伪元素来使其按需要工作,以便仅伪元素会受到影响。

查看摘要中的评论:

.main {
  position: relative;   /* Added */
  width: 300px;
  height: 300px;
  list-style: none;
}

.main::before {   /* Added */
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: blue;
  transition: 0.5s;
}

.button {
  position: absolute;
  top: 35%;
  height: 30px;
  width: 120px;
  display: none;
  z-index: 99;
  background-color: black;
  color: white;
}

.icon {
  width: 30px;
  position: absolute;
  z-index: 99;
  display: none;
  width: 100px;
}

.main:hover>.button {
  display: block;
  /* filter: none; Commented */
}

.main:hover>.icon {
  display: block;
  /* filter: none; Commented */
}

.main:hover::before {   /* Modified */
  filter: brightness(50%);
}
<li class="main">
  <img src="https://help.seesaw.me/hc/en-us/article_attachments/204081043/bear.png" class="icon" />
  <a class="button" href="#">Button</a>
</li>

希望有帮助。

答案 1 :(得分:0)

我将为该任务建议使用伪元素。您的 .main 类使用 position:relative 保留父位置,而图像和按钮则依赖于 position absolute 。 将鼠标悬停在具有 .main 类的元素上,添加伪元素 :: before 并按照下面的代码所述应用必要的样式。

.main {
  width:300px;
  height:300px;
  list-style:none;
  position:relative;
  background-color:blue;
}

.button {
    position: absolute;
    top: 35% ;
    height: 30px;
    width: 120px;
    display: none;
    z-index: 99;
    background-color:black;
    color:white;
}

.icon {
    width: 30px;
    position: absolute;
    z-index: 999999;
    display: none;
    width:100px;
}

.main:hover>.button {
  display: block;
}

.main:hover>.icon {
  display: block;
}

.main:hover::before {
  content: "";
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  position:absolute;
  background-color:blue;
  transition: 0.5s;
  filter: brightness(50%);
}
<li class="main">
<img src="https://help.seesaw.me/hc/en-us/article_attachments/204081043/bear.png" class="icon" />
<a class="button" href="#">Button</a>
</li>