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
4 Answers
Reset to default 8You 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