导航菜单
首页 >  images/2024xs/jsx.png  > 3 Ways to Set Background Image in Next.js

3 Ways to Set Background Image in Next.js

This succinct, practical article will show you some different ways to set an image background in Next.js 13 and above (with the /app directory). Without any further ado (such as explaining what Next.js is or talking about its history), let’s get straight to the main points.

Table Of Contents1Importing the image as a file and using inline styles 2Using the next/image component 3Using TailwindCSS 4ConclusionImporting the image as a file and using inline styles

This solution involves importing the image file from the public folder and using its src property to set the background image of a component. The steps to implement this idea are listed below:

Place your image file in the public folder of your Next.js project.Import the image file in your component file using import backgroundImage from "/your-image-name.png";Use the src property of the imported image object to set the background image of a component using inline styles: backgroundImage: url(${backgroundImage.src})

Example:

// src/app/page.tsx// import the image file from public folder// make sure to replace my image path with your ownimport backgroundImage from "../../public/background.png";export default function Home() { return ( Welcome to Sling Academy! );}

Output:

This solution is simple and straightforward. You can use any image format supported by Next.js, such as JPG, PNG, SVG, etc.

Using the next/image component

This approach makes use of the next/image component to render an image as a background of a component. It works well with both static (in the public folder) and dynamic images (fetched from API) images. It also leverages the benefits of next/image component, such as automatic resizing, optimization, and lazy loading of images. However, the tradeoff is that you’ll have to write some extra CSS to position and style things. Some CSS properties like backgroundSize and backgroundRepeat can’t be used with the image.

To implement this solution, you can follow these steps:

Import next/image in your component file using import Image from "next/image";If you want to use an image from the internet, you have to specify its hostname in your next.config.js file.Use the next/image component to render an image from the public folder or an external source using the src and fill props. For instance: Use CSS properties like position, zIndex, and opacity to adjust the appearance of the image and the component, like this: position: "relative", zIndex: -1, opacity: 0.5

In the coming example, we’ll use this image:

https://api.slingacademy.com/public/sample-photos/8.jpeg

Therefore, we need to add api.slingacademy.com to the images block in next.config.js as shown below:

/** @type {import('next').NextConfig} */const nextConfig = {images: {domains: ['api.slingacademy.com'],}}module.exports = nextConfig

Example screenshot:

The code:

// src/app/page.tsximport Image from "next/image";export default function Home() { return (// The parent div{/* The child element */}Welcome to Sling Academy!);}Using TailwindCSS

Since Next.js 13, TailwindCSS integration is available as a choice and built-in feature when you initialize your project. You can use the className attribute to apply Tailwind’s utility classes to your elements. For example, you can use classes like bg-cover, bg-center, bg-fixed, etc. to adjust the background image.

To use a dynamic background image, you need to use the style props and provide the URL of the image as an inline style. You can’t use string concatenation to create CSS class names in TailwindCSS. The following will NOT work:

Some content

Here’s the way to go:

{/* Your other components here */}Conclusion

You’ve learned several techniques to set an image background in Next.js. You can improve the code examples to make them even better and cleaner. Add some things, remove some things, and modify some lines of code to see what happens next.

This tutorial ends here. If you find something outdated or incorrect, please let me know by leaving a comment. Happy coding & have a nice day!

Next Article:How to use Font Awesome with Next.js

Previous Article:How to Use MUI (Material UI) in Next.js 14

Series:Working with CSS in Next.js

Next.js

Related Articles

Fixing Next.js Error: Link is not defined Solving Next.js Image Component Error with CSS Classes Fixing Data Update Issues in Next.js Production Fixing Next.js Undefined ENV Variables in Production Build Solving Next.js SyntaxError: Unexpected token ‘export’ Next.js Error: Found Page Without a React Component as Default Export – How to Fix Fixing Next.js Error: Blank Page on Production Build Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide Next.js Issue: useEffect Hook Running Twice in Client Fixing ‘self’ is not defined error in Next.js when importing client-side libraries How to Dockerize a Next.js App for Production How to set up Next.js with Docker Composer and Nginx

相关推荐: