我在让 css 样式按预期应用时遇到一些麻烦。我正在用 ReactJS/NextJS 编写这个应用程序。我正在尝试创建一个显示图像的组件,其中文本位于图像顶部。我希望我应用的 CSS 样式能够正常工作,因为我已经通过 w3schools 测试了这些样式。我附上我在 w3schools 中所做的操作、我当前在代码中所做的操作以及 localhost:3000 中的所有内容的屏幕截图。带有 imageContainer1 的 div 在 css 文件中应用了背景图像,但该图像未出现在屏幕上。确实出现的图像来自具有内联样式的第二个 div(我从某处复制的,不记得了)。问题是,当我删除内联样式并将样式移动到样式标记内或 css 文件中时,样式不再像内联那样应用。当我移动它时,样式不一致,这很令人困惑。
唉,我们的目标是以视口的全宽显示图像,文本位于图像顶部。我很感激任何指点。
import styles from './HomeContent.module.css'
const Home = () => {
return (
<div className={styles.container}>
<div className={styles.imageContainer1}></div>
<p className={styles.text}>
text
</p>
</div>
)
}
export default Home
.imageContainer1 {
background-image: url(../public/redtesla.jpg);
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
max-width: max-content;
/* position: relative;
text-align: center;
background-color: blue; */
}
.container {
height: 100%;
margin: 0;
}
.text{
position: 'absolute';
top: '25%';
left: '10%';
color: "red";
}
嘿,如果您仍在寻找解决方案,我通常在 NextJs 中做的是:
从 NextJs 导入图像元素
import Image from "next/image";
然后使用 fill 属性代替 width 和 height 属性
fill={true}
然后转到要在该图像上方显示的文本元素,并将位置设置为相对位置并为其指定高度。
然后给出该文本元素
align-content: center;
如果您需要有关图像道具的任何信息,请访问 https://nextjs.org/docs/app/api-reference/components/image
‘使用客户端’
从“next/image”导入图像 从'react'导入{useEffect}
导出默认函数 Carousel() {
return (
<>
<div id="carouselExampleAutoplaying" className="carousel slide" data-bs-ride="carousel">
<div className="carousel-inner">
<div className="carousel-item active">
<Image src={img} className="d-block w-100" fill={true} objectFit="cover" alt="..."/>
<h1 className={classes.h1}>Lorem Ipsum</h1>
</div>
<div className="carousel-item">
<Image src={img2} className="d-block w-100" fill={true} objectFit="cover" alt="..."/>
<h1 className={classes.h1}>Lorem Ipsum </h1>
</div>
<div className="carousel-item">
<Image src={img} className="d-block w-100" fill={true} objectFit="cover" alt="..."/>
<h1 className={classes.h1}>Lorem Ipsum</h1>
</div>
</div>
<button className="carousel-control-prev" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="prev">
<span className="carousel-control-prev-icon" aria-hidden="true"></span>
<span className="visually-hidden">Previous</span>
</button>
<button className="carousel-control-next" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="next">
<span className="carousel-control-next-icon" aria-hidden="true"></span>
<span className="visually-hidden">Next</span>
</button>
</div>
</>
);
}
.h1 {
position: relative;
height: 60vh;
align-content: center;
width: 70vw;
text-align: center;
margin-left: auto;
margin-right: auto;
color: white;
}