正如标题所说。我正在努力思考如何才能达到预期的效果。
import React from "react";
import Image from "next/image";
import heroBackground from "../public/hero-background.png";
const Hero = () => {
return (
<div className='relative min-h-content max-w-[1920px] '>
<Image
src={heroBackground}
alt='Hero Background'
className='absolute top-0 left-0'
/>
<div className='p-24'>
<h1 className='absolute text-4xl font-bold text-black'>HERO TEXT</h1>
</div>
</div>
);
};
export default Hero;
我已经尝试了所有我能想到的方法,并查找了很多解决方案。然而,它们似乎都不适合我。当我之前尝试实现这一目标时,我在一些在线工具的帮助下想出了这个。
import React from "react";
import Image from "next/image";
const Backdrop = ({ children, title, backgroundImg }) => {
return (
<>
{backgroundImg || title ? (
<div className='relative flex items-center min-h-content bg-fixed bg-cover'>
<Image
src={backgroundImg}
alt={backgroundImg}
className='z-[-1] min-h-[50px]'
/>
<h1 className='absolute top-[35%] left-[10%] w-[60%]'>{title}</h1>
<div className='absolute'>{children}</div>
</div>
) : (
<div>{children}</div>
)}
</>
);
};
export default Backdrop;
必须有比这更简单、更简单的方法才能实现背景图像效果。
使用
background-image
代替相对位置和绝对位置
此外,如果您使用 NextJS,您应该将
public/
引用为您的根 Web 目录,例如:
../public/hero-background.png
应该是 hero-background.png
const Hero = () => {
return (
// consider having a min-w and min-h value too if u want to see the whole image
// you should not need relative and absolute anymore
<div className='min-h-content max-w-[1920px] bg-[url("hero-background.png")]'>
<div className='p-24'>
<h1 className='text-4xl font-bold text-black'>HERO TEXT</h1>
</div>
</div>
);
};