Leveraging createMuiTheme to customize default styles for divs, paragraphs, and the body element

Seeking guidance on customizing a Material UI Theme

I aim to modify the default styles for elements like <body>. Currently, at the root of my React tree:

import theme from './mui-theme'

ReactDOM.render(
   <Router>
     <ThemeProvider theme={theme}>
       <StylesProvider injectFirst>
         {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
         <CssBaseline />
         <App />
       </StylesProvider>
     </ThemeProvider>
   </Router>,
   document.getElementById('root'),
);

The provided theme does not include styling for 'body1'

const theme = useTheme() reveals that it is defined as:

typography:
  body1:
    fontFamily: "Roboto,"Helvetica Neue""
    fontSize: "1rem"
    fontWeight: 400
    lineHeight: 1.5

This 'body1' setting is desired but currently requires using the Typography tag with variant='body1'. Otherwise, text within a div follows the styling set by CssBaseline, such as font-size: .875rem;, which I wish to change.

Is there a way to override CssBaseline styling using createMuiTheme? I have tried adding:

body: {
    fontSize: '1rem',
  },

While this modification shows up in console.log(theme), how can I ensure that the <body> tag actually utilizes this style?

Answer №1

Here is an illustration of how you can customize the CssBaseline:

import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";

const styles = theme => ({
  "@global": {
    body: {
      ...theme.typography.body1
    }
  }
});

function CustomCssBaseline() {
  return null;
}

CustomCssBaseline.propTypes = {
  classes: PropTypes.object.isRequired
};

export default withStyles(styles)(CustomCssBaseline);

import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@material-ui/core/CssBaseline";
import CustomCssBaseline from "./CustomCssBaseline";

function App() {
  return (
    <>
      <CssBaseline />
      <CustomCssBaseline />
      <span>
        This text within the body will now have the body1 styling applied by
        CustomCssBaseline.
      </span>
    </>
  );
}
ReactDOM.render(<App />, document.querySelector("#root"));

https://codesandbox.io/s/material-demo-vkl08?fontsize=14

Reference: https://material-ui.com/styles/advanced/#global-css

Answer №2

Special thanks to @RyanCogswell for sharing their insights in this response. When using MUI v5, you can achieve the same effect with the following code:

const theme = createTheme({
  components: {
    MuiCssBaseline: {
      styleOverrides: `
        h1 {
          color: grey;
        }
      `,
    },
  },
})

Alternatively, you can utilize the GlobalStyles component. More information can be found here:

https://mui.com/material-ui/customization/how-to-customize/#4-global-css-override

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React PDF unable to display PDF files on IOS 15.5

I am currently utilizing react-pdf to display a PDF within a React application, which is then presented through a WebView on both iOS and Android platforms. The PDF rendering functions properly on Android. However, in iOS, an error message appears statin ...

Using CSS with multiple background images and the "contain" property

Hey there! Is it possible to have multiple background images stacked on top of each other within a single div? I want the images to resize automatically with "background-size: contain;". Have you tried this before? background-image: url('../img/ima ...

React Native is designed to easily stick an image to the bottom of the screen

I am struggling to make the image stick to the bottom of the app without any extra space underneath it. Despite trying various solutions from Stack Overflow, I have been unable to achieve the desired result. The issue is the large white space between the r ...

Is there a way to prevent the second ul from appearing?

Seeking assistance with navigation. When clicking on the "Athletics" tab in the provided link, the second ul displays. Is there a method to hide this second ul and have it only appear upon hovering? ...

Modify the cursor pointer style in MUI Link using React

Is there a way to customize the cursor pointer style on MUI Link? I've tried using the 'cursor: pointer' style but it doesn't seem to work. Here is my code: <Link style={{ cursor: 'pointer' }} onClick={() => { ...

Background styling for TreeItems in Material-UI's TreeView

Just recently, I encountered an interesting phenomenon while working with the following dependencies: "@material-ui/core": "4.8.3", "@material-ui/lab": "4.0.0-alpha.37" After deselecting a TreeItem and selecting another one, I noticed that there was no lo ...

Tips for accurately relocating elements within a tooltip

Currently, I am working on implementing a like model within a Rails application. In order to display which user liked the bonus, I have incorporated foundation tooltip. Below is the code snippet: - avatars = bonus.like_user_avatars.map { |avatar| image_t ...

Using the class for jQuery validation as opposed to the name attribute

I am looking to implement form validation using the jquery validate plugin, but I am facing an issue with using the 'name' attribute in the html since it is also used by the server application. Specifically, I want to restrict the number of check ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Use jQuery to smoothly scroll a div

I created a container using a <div> element which is divided into 3 inner divs. The first two inner divs are meant to serve as previous and next buttons, with ids of prev and next respectively. At the bottom, there are 3 more inner divs, each with un ...

Occasions focused on the <input type="file"> feature

Looking for a way to write a file input in React that accepts CSV files, validates them, and prevents upload if there are errors? Check out the code snippet below: <CustomInput type="file" id="fileBrowser" name="file" label={filename || 'Choos ...

Jquery Query: Is it possible to incorporate variables into CSS properties?

I manage a website that supports multiple languages, and I want to adjust the position of my container based on the selected language. To achieve this, I attempted the following code: prop = lang == 'ar' ? 'right' : 'left'; $ ...

It appears that the font in style.css is not being updated properly and seems to resemble

My issue lies within my CSS code. The text on my website is not displaying correctly and seems to be ignoring the styling that I have applied. Even though I have used similar styling on other buttons which look fine, this specific text element is causing p ...

In React, the clearInterval() function does not effectively clear intervals

Currently, I am implementing the following code: startInterval = () => { this.interval = setInterval(this.intervalFunction, 10000) } stopInterval = () => { clearInterval(this.interval) } However, a problem arises when I invoke the stopInte ...

The Role of Filling in a Process

I am looking to create a rectangle that fills up gradually every day, increasing by 1% each time. This is the basic concept. My main struggle is figuring out how to fill it up. I need the rectangle to increase by 1% of its width each day. So essentially, ...

Tips for arranging buttons horizontally in Angular

After adding a third button, I noticed that the buttons were now displaying in a column instead of a row. html: <div class="creator-button-container" *ngIf="isCurrentUserTheChannelCreator"> <div *ngIf="isChannelE ...

Maintain the basic structure while ensuring divs are properly aligned

Behold, my div structure! ONE // at the top level TWO THREE // two divs side by side in the middle level FOUR // residing at the bottom <div id="ONE"> <div></div> <div><img src="logo.png"></div> </div> < ...

Transferring Chart Div Titles Above Bars

Is there a way to adjust the layout of an HTML bar chart so that the names or labels appear outside of the bars, tagged to the left end? <!DOCTYPE html> <style> .chart div { font: 10px Ubuntu; background-color: white; text-align: right; ...

Tips on deleting excess space in between Material-UI Grid Rows

https://i.stack.imgur.com/nASqM.pngWhen attempting to utilize the Material UI grid system, I encountered an odd spacing issue when using grid direction='row'.https://i.stack.imgur.com/sl59V.png const useStyles = makeStyles((theme) = ...

Ways in which breakpoint.value can be utilized?

I've created a platform to manage employee activities, and I want it to be fully responsive across all devices. For instance, if you wish to tailor the site for screens labeled as "sm" and "xs," you can use the following code: [theme.breakpoints.down ...