如何用:after伪类隐藏按钮上CSS精灵图的多余部分?
CSS精灵图竖版按钮防相邻内容泄露解决方案
问题背景
我有一系列横向拼接的CSS精灵图,包含横版、竖版两种照片,要在按钮上无失真展示。目前横版显示正常,但竖版照片因宽度较窄,按钮右侧会露出精灵图里的下一张内容,想用:after伪类快速解决。
实现方案
核心是用:after伪类给竖版按钮添加同背景色的右侧遮罩,精准盖住超出竖版图片宽度的区域,同时不影响按钮交互。
修改后的CSS代码
/* Global constants */ :root { --portWidth: calc(2052px / 4); /* 竖版照片宽度(原图/4) */ --landWidth: calc(3264px / 4); /* 横版照片宽度(原图/4) */ } figure { display: block; float:left; border-width:thin; } figcaption {background-color:yellow;} /* 按钮基础样式调整:添加相对定位,为伪类提供定位基准 */ .thumb { position: relative; } /* 遮罩伪类通用样式:默认隐藏,仅竖版按钮启用 */ .thumb::after { content: ""; display: none; position: absolute; top: 0; right: 0; bottom: 0; /* 计算遮罩宽度:按钮总宽度 - 竖版缩略图按比例缩放后的宽度 */ width: calc(30em - (var(--portWidth) / var(--landWidth) * 30em)); background-color: #fff; /* 替换为你的页面背景色,确保完全遮挡 */ z-index: 1; /* 确保遮罩在精灵图背景上方 */ } #thumb1, #thumb2, #thumb3 { background: url("bates-sprite.jpeg"); background-repeat: no-repeat; width: 30em; height: 30em; background-size: cover; float: left; margin-right: 1.5em; } /* 横版照片样式 */ #img1 { object-position: 0 0; width: var(--landWidth); height: 612px; /* 原图2448/4 */ } #thumb1 { background-position: 0 0; } /* 横版照片样式 */ #img2 { object-position: calc( var(--landWidth) * -1) 0; width: var(--landWidth); height: 612px; } #thumb2 { background-position: -30em 0; } /* 竖版照片样式 */ #img3 { object-position: calc( ( var(--landWidth) * -1) * 2) 0; width: var(--portWidth); height: calc(3101px / 4); /* 原图3101/4 */ } #thumb3 { background-position: -60em 0; } /* 启用竖版按钮的遮罩 */ #thumb3::after { display: block; }
关键说明
- 定位基准:给
.thumb添加position: relative,让伪类能基于按钮的边界定位。 - 遮罩宽度计算:通过公式算出按钮中竖版图片实际占有的宽度,用按钮总宽度减去这个值,得到需要遮罩的区域宽度,刚好盖住右侧会露出的下一张精灵图内容。
- 背景色匹配:遮罩的
background-color必须和按钮所在区域的背景色一致,否则会出现突兀的色块。 - 按需启用:仅给竖版按钮
#thumb3显示遮罩,横版按钮默认隐藏伪类,避免多余样式。
内容的提问来源于stack exchange,提问作者Hobbyist
相关产品推荐
相关产品推荐

