循环生成的hr元素className无法被CSS生效问题求助
问题:循环生成的hr元素CSS样式不生效
我通过循环生成了10个带horizontal类名的<hr>元素,元素已在页面正常显示,但对应的CSS样式完全无法生效,页面中其他类名的样式均正常工作。
React代码
import React from "react"; import "./home.css"; import myPicture from "../../assets/picofme.png"; const HorizontalLines = ({ numberOfLines }) => { const lines = []; for (let i = 0; i < numberOfLines; i++) { lines.push(<hr key={i} className="horizontal" />); } return <div>{lines}</div>; }; const Home = () => { return ( <section id="home"> <div className="homeContent"> <span className="hi">Hello,</span> <span className="intro"> I'm <span className="Me">Me</span> <br /> software </span> <p className="introPara"> This is my experince developer.{" "} <p>Here are my solutions</p> </p> </div> <img src={myPicture} alt="profile" className="myPicture" /> <HorizontalLines numberOfLines={10} /> </section> ); }; export default Home;
CSS代码
#home { height: calc(100vh - 4rem); width: 100%; max-width: 98%; margin: 0 auto; overflow: hidden; position: relative; } .horizontal { z-index: -4; color: #22c8ff; }
解决方案
1. 覆盖<hr>的默认浏览器样式
<hr>元素自带浏览器默认的边框和样式,单纯设置color属性通常不会直接生效,需要明确定义边框或背景:
.horizontal { z-index: -4; color: #22c8ff; /* 清除默认边框 */ border: none; /* 使用color值设置顶部边框 */ border-top: 1px solid currentColor; /* 可选:调整行间距 */ margin: 1rem 0; }
2. 直接设置背景色替代边框
如果不需要依赖color属性,也可以直接定义背景色:
.horizontal { z-index: -4; /* 固定高度 */ height: 1px; /* 清除默认边框 */ border: none; /* 设置线条颜色 */ background-color: #22c8ff; margin: 1rem 0; }
3. 检查样式优先级(可选)
如果以上方法无效,可能是样式被其他更高优先级的选择器覆盖,可以通过提升选择器优先级解决:
/* 利用父元素ID提高优先级 */ #home .horizontal { z-index: -4; border-top: 1px solid #22c8ff; margin: 1rem 0; }
内容的提问来源于stack exchange,提问作者Alex010
相关产品推荐
相关产品推荐

