如何使用::before伪元素在cookie通知div顶部添加重复阴影图片
我有一张小图片,希望将其重复平铺,使其呈现为cookie通知div顶部的阴影效果。请问如何将该图片定位在id为cookieConsent的div顶部作为阴影?

解决方案一:用CSS伪元素实现顶部阴影
通过给#cookieConsent添加:before伪元素,把阴影图片水平平铺在容器顶部,不会干扰原有内容布局:
#cookieConsent { width: 100%; background-color: #474540F2; position: fixed; bottom: 0; left: 0; right: 0; display: block; /* 改为block方便预览效果 */ z-index: 9999; padding-top: 8px; /* 根据阴影图片高度调整,避免内容被遮挡 */ } /* 新增顶部阴影伪元素 */ #cookieConsent:before { content: ""; position: absolute; top: 0; left: 0; right: 0; height: 8px; /* 匹配阴影图片的高度 */ background-image: url('https://i.sstatic.net/aucgJ.png'); background-repeat: repeat-x; /* 水平方向重复平铺 */ } .cookieContainer { padding: 16px; display: flex; align-items: center; justify-content: center; gap: 16px; font-size: 12px; } .cookieConsent-txt { color: #FFFFFF; width: calc(100% - 101px); /* 修正calc语法的空格问题 */ margin: 0; } #cookieConsent a.cookieConsentOK { width: 85px; height: 56px; background: #FFFFFF; display: inline-block; padding: 0 20px; display: flex; align-items: center; justify-content: center; }
HTML无需修改:
<div id="cookieConsent"> <div class="cookieContainer"> <p class="cookieConsent-txt"> 本网站使用Cookie </p> <a class="cookieConsentOK">同意Cookie</a> </div> </div>
解决方案二:直接给容器设置顶部背景
如果不想用伪元素,也可以直接给#cookieConsent添加背景图片,让它固定在顶部水平重复:
#cookieConsent { width: 100%; background-color: #474540F2; position: fixed; bottom: 0; left: 0; right: 0; display: block; z-index: 9999; background-image: url('https://i.sstatic.net/aucgJ.png'); background-repeat: repeat-x; background-position: top left; padding-top: 8px; /* 给阴影预留空间,防止内容被遮挡 */ } /* 其余样式保持不变 */ .cookieContainer { padding: 16px; display: flex; align-items: center; justify-content: center; gap: 16px; font-size: 12px; } .cookieConsent-txt { color: #FFFFFF; width: calc(100% - 101px); margin: 0; } #cookieConsent a.cookieConsentOK { width: 85px; height: 56px; background: #FFFFFF; display: inline-block; padding: 0 20px; display: flex; align-items: center; justify-content: center; }
内容的提问来源于stack exchange,提问作者Awa
相关产品推荐
相关产品推荐

