首页 > 解决方案 > 在 CSS 中为页面上的每个元素添加叠加颜色

问题描述

我想为任意 html 页面上的每个元素添加叠加颜色,并使其不断着色。这样当我悬停元素时,我可以删除覆盖,从而突出显示悬停的元素,如下所示:

突出显示的元素

我希望我能够做这样的事情:

* {
  position: relative;
  z-index: 1;
}

*:after {
  content: ''; 
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  background: rgba(0, 0, 0, 0.1);
}

但是你最终得到的嵌套元素有多个覆盖,所以它看起来并不那么干净。最终看起来更像这样:

嵌套叠加

我能想到的唯一另一种选择是覆盖整个页面的某种覆盖元素,然后当您悬停一个元素时,它会在其上添加某种反覆盖元素。

有什么想法吗?

标签: htmlcss

解决方案


您可以添加一个具有大 z-index 的叠加层,一旦悬停一个元素,您就可以增加其 z-index 以将其移动到上方:

body:before {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  z-index: 999;
  pointer-events: none;/* This will do all the magic !*/
}

body *:hover {
  position: relative;
  z-index: 1000;
  background: #fff;
}
<h1>tile</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla id rhoncus arcu. Phasellus venenatis ex nulla, nec feugiat nibh sodales at. Pellentesque vehicula eu arcu at varius</p>

<div>
  <h2>another title</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla id rhoncus arcu. Phasellus venenatis ex nulla, nec feugiat nibh sodales at. Pellentesque vehicula eu arcu at varius</p>
</div>


推荐阅读