如何使用HTML和CSS为clip-path/clip裁剪区域添加透明度效果
给clip裁剪区域添加透明度效果的实现
你需要调整遮罩层的层级与裁剪规则,让半透明遮罩刚好匹配裁剪区域的范围,不会溢出到未裁剪的部分。
以下是修改后的可运行代码:
CSS代码
.item--clip .demo { width: 200px; height: 250px; } .item--clip .has-mask { position: absolute; clip: rect(10px, 190px, 190px, 10px); } /* 匹配裁剪区域的遮罩规则 */ .item--clip .demo::before { clip: rect(10px, 190px, 190px, 10px); background: #000; /* 可自定义遮罩颜色 */ z-index: 1; /* 层级高于图片,才会覆盖在裁剪区域上方 */ } /* Common ------------------------------------------- */ .item { position: relative; margin-bottom: 2em; padding-bottom: 2em; padding-right: 3em; border-bottom: 1px solid #DDD; } .item::before { position: absolute; right: 0; top: 0; font: 2rem/1 Georgia, serif; color: #EEE; } .item::after { content: ''; display: table; width: 100%; } .demo { position: relative; float: left; margin-right: 30px; } .demo::before { content: ''; display: block; position: absolute; z-index: -2; top: 0; right: 0; bottom: 0; left: 0; opacity: 0; transition: .7s; } .text { padding-left: 230px; } .item:hover .demo::before { opacity: .4; }
HTML代码
<div class="wrapper"> <div class="item item--clip"> <div class="demo"> <img src="https://img-fotki.yandex.ru/get/5607/5091629.6b/0_612e6_b9039c0d_M.jpg" alt="" class="has-mask" /> </div> </div> </div>
核心修改说明:
- 给
.demo::before添加和裁剪图片完全一致的clip属性,保证遮罩显示范围和裁剪区域完全重合 - 将遮罩的z-index调整为高于图片的层级,确保半透明效果能覆盖在裁剪区域上
- 把原全局的
:hover ::before选择器修改为指定.demo::before,避免影响其他元素的伪元素样式
内容的提问来源于stack exchange,提问作者Tsokoloy
相关产品推荐
相关产品推荐

