最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to add background image to box in mui - Stack Overflow

programmeradmin2浏览0评论

I am trying to add a background image to Box component of mui but it dosen't work I am providing my code

const Main = () => {
  return (
    <Box 
     sx={{backgroundImage:'images/cover.jpeg'}}
     height='385px'
    >
      
    </Box>
  )
}

I am trying to add a background image to Box component of mui but it dosen't work I am providing my code

const Main = () => {
  return (
    <Box 
     sx={{backgroundImage:'images/cover.jpeg'}}
     height='385px'
    >
      
    </Box>
  )
}
Share Improve this question edited Jun 12, 2023 at 7:16 Steve G 13.4k7 gold badges44 silver badges59 bronze badges asked Dec 21, 2022 at 4:28 Pratik ShindePratik Shinde 691 gold badge1 silver badge4 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 8

You are well on track. To employ this successfully, you can proceed as follows;

import  cover from "./images/cover.jpeg";
 const Main = () => {
  return (
   <Box
   sx={{
    backgroundImage:`url(${cover})`,
    backgroundRepeat: "no-repeat",
    backgroundSize: "cover",
    height: "385px",
    }}
   >
   <Box/>
  )    
}

The assumption here is that the path provided for the import is correct("./images/cover.jpeg"). You can supply additional styling such as width to the image as desired.

You're not far from it. You just need to add the path to the file preceded by url, for example:

const Main = () => {
  return (
    <Box
      sx={{
        backgroundImage: "url('images/cover.jpeg')",
        backgroundRepeat: "no-repeat",
        height: '385px',
        width: '385px'
      }}
    >
    
    </Box>
  );
};

(assuming images/cover.jpeg is the correct path to your image.)

Working CodeSandbox: https://codesandbox.io/s/mui-box-background-image-wcseex?file=/demo.js

What worked for me was:

<Box sx={{
            backgroundImage: `url(${calltoActionBg.src})`,
        }}>CallToAction</Box>

Without the ".src" it was rendering as [Object,Object]

const Main = () => {
  return (
    <Box
          sx={{
            backgroundImage: `url("./images/cover.jpeg")`,
            backgroundPosition: `right bottom`,
            backgroundRepeat: `no-repeat`,
            backgroundSize: `300px 300px`,
            height: "100%",
            width: "100%",
          }}
        > 
      
    </Box>
  )
}

Make sure image url is correct and need to give some size to adjust the layout

发布评论

评论列表(0)

  1. 暂无评论