React中CSS的::before伪元素无效问题求助
解决React中img元素::before伪元素不生效的问题
问题根源
<img>属于替换元素,这类元素的内容由外部资源(比如你的图片文件)决定,浏览器默认不会为其生成::before或::after伪元素,所以你写的img::before规则完全不会生效。
修复方案
方案1:给img套容器,为容器添加伪元素
修改React组件,用容器包裹img,将伪元素绑定到容器上:
React代码:
import React from "react"; import "./body-section.css"; import background from "../etc/Image-robot.jpg"; const Body = () => { return ( <div className="body"> <div className="bdy-socials-section"> <div className="img-wrapper"> <img src={background} id="bg-img"></img> </div> </div> </div> ) } export default Body;
CSS代码:
.bdy-socials-section .img-wrapper { position: relative; width: 55vw; height: 80vh; left: 50px; } .bdy-socials-section .img-wrapper > img { width: 100%; height: 100%; transform: SkewY(5deg); } /* 给容器添加伪元素,这里可以自定义样式 */ .bdy-socials-section .img-wrapper::before { content: ""; display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.2); }
方案2:用div替代img,通过背景图加载图片
如果不需要<img>的alt等专属属性,可以直接用div承载背景图,伪元素可直接作用于该div:
React代码:
import React from "react"; import "./body-section.css"; import background from "../etc/Image-robot.jpg"; const Body = () => { return ( <div className="body"> <div className="bdy-socials-section"> <div className="bg-img" style={{ backgroundImage: `url(${background})` }} ></div> </div> </div> ) } export default Body;
CSS代码:
.bdy-socials-section .bg-img { width: 55vw; height: 80vh; transform: SkewY(5deg); position: relative; left: 50px; background-size: cover; background-position: center; } .bdy-socials-section .bg-img::before { content: ""; display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; /* 自定义伪元素样式 */ border: 2px solid #fff; }
关键提示
伪元素必须设置content属性(哪怕是空字符串)才会生效,你之前的代码虽然加了content: "",但因为<img>的替换元素特性,规则根本不会被浏览器解析。
内容的提问来源于stack exchange,提问作者user16703040
相关产品推荐
相关产品推荐

