I want to set a background image in the body of my web app using material-ui-next's CSS-in-JS, withStyles, or themes? I would like to avoid using an external CSS file if possible.
How to set background-image for the body element using CSS ? In this article, we set the image into the background using CSS property. The background-image property is used to set one or more background images to an element. By default, it places the image on the top left corner. To specify two or more images, separate the URLs with a comma.
The background-image property is used to set one or more background images to an element. By default, it places the image on the top left corner. To specify two or more images, separate the URLs with a comma. Property value: It holds the URL of an image that you want to use as background image.
This tutorial assumes that you already created a new react project using create-react-app. In the above example first, we imported car image from the images folder then we added it to the div element using backgroundImage css property. If you don’t like adding background images using inline styles we can also add using external css styles.
You can inject css into the outer scope with "@global" using withStyles from "@material-ui/core/styles"
import React, { Fragment } from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import { withStyles } from "@material-ui/core/styles";
import Main from "./Main";
const styles = theme => ({
"@global": {
body: {
backgroundImage: "url('/media/landing.jpg')",
backgroundRepeat: "no-repeat",
backgroundPosition: "center center",
backgroundSize: "cover",
backgroundAttachment: "fixed",
height: "100%"
},
html: {
height: "100%"
},
"#componentWithId": {
height: "100%"
}
}
});
const App = () => {
return (
<Fragment>
<CssBaseline />
<Main />
</Fragment>
);
};
export default withStyles(styles)(App);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With