CSS如何添加背景图且不遮挡上方的span文字与图标
你可以通过多层背景叠加的方案实现需求:在背景图上层叠加一层半透明遮罩,同时调整文字颜色保证对比度,就能做到背景图正常显示且不遮挡上层的文字、图标。
样式修改(styles.css)
调整背景规则为多层结构,同时给文字容器新增白色字体配置:
.App { font-family: sans-serif; text-align: center; } .photo__wrapper__img { display: flex; flex-direction: column; align-items: center; justify-content: center; margin: auto; width: 150px; height: 150px; border-radius: 50%; /* 多层背景顺序:先写的层在上,半透明遮罩覆盖背景图 */ background: linear-gradient(rgba(60, 67, 74, 0.5), rgba(60, 67, 74, 0.5)), url(替换为你的背景图地址); background-repeat: no-repeat; background-position: center; background-size: cover; cursor: pointer; } .__photo__wrapper__img__label-container { text-align: center; color: #fff; }
动态背景图适配(App.js)
如果背景图是动态生成的,不需要写死在CSS中,可以直接在JSX的style属性中注入配置:
import "./styles.css"; import CloudUploadOutlinedIcon from "@material-ui/icons/CloudUploadOutlined"; export default function App() { // 可替换为动态接口返回的背景图地址 const customBgUrl = "你的背景图地址"; return ( <div className="App"> <div className="photo__wrapper__img" style={{ background: `linear-gradient(rgba(60, 67, 74, 0.5), rgba(60, 67, 74, 0.5)), url(${customBgUrl})`, backgroundRepeat: "no-repeat", backgroundPosition: "center", backgroundSize: "cover" }} > <div className="__photo__wrapper__img__label-container"> <div> <CloudUploadOutlinedIcon style={{ color: "white" }} /> </div> <span>Click here to change photo</span> </div> </div> </div> ); }
如果需要调整文字的清晰程度,只需要修改半透明遮罩的透明度参数(即rgba的最后一位数值,数值越大遮罩越暗,文字越清晰)。
内容的提问来源于stack exchange,提问作者CCCC
相关产品推荐
相关产品推荐

