CSS知识点总结
一、利用CSS filter实现一个hover凸显当前元素,模糊其他元素的效果
html:
<div class="boxes">
<div class="filter">看到见吗</div>
<div class="filter">看到见吗</div>
<div class="filter">看到见吗</div>
<div class="filter">看到见吗</div>
<div class="filter">看到见吗</div>
</div>
css:
.filter {
display: inline-flex;
justify-content: center;
align-items: center;
position: relative;
width: 200px;
height: 200px;
margin-right: 20px;
color: white;
}
.filter:hover::before {
transform: scale(1.05);
}
.boxes:hover>.filter:not(:hover)::before {
filter: blur(5px) opacity(0.8) brightness(0.8);
}
.filter::before {
/* 防止背景遮住元素内容 */
z-index: -1;
content: '';
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
border-radius: 20px;
filter: blur(0) opacity(1);
background-image: url('./filter.jpg');
background-size: 200px 200px;
transition: all 300ms linear;
}
首先,CSS
的filter
属性可以为元素添加blur
和opacity
属性,但是这样会导致其子元素也变得模糊。因此,不能对元素本身使用filter
,那可以对伪元素使用filter
,可以使用绝对定位且z-index=-1
,这样就不会影响元素内容的显示。同时,这样hover
时,变模糊的就只有before
伪元素。
这里有个小知识点:定位元素使用
top: 0; left: 0; bottom: 0; right: 0;
的目的是什么呢?可以想象该元素为了满足四个条件就会“铺满”相对父元素,因此,这样写和写width: 100%; height: 100%;
的效果是一样的。
此外,.boxes:hover>.filter:not(:hover)::before
这里写.boxes:hover>
的目的是鼠标不处于悬浮状态时,不会进行模糊(也是为了增加CSS权重)。