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

Verifying the status of a checkbox label in Java using Selenium

I am currently working on an automation project using Selenium and I'm struggling to figure out how to check the status of a checkbox input. Has anyone else encountered this issue before? Here is a sample code snippet in JavaScript with jQuery: $("i ...

Disabling trailing slash to false on a single page in Next.js: A step-by-step guide

Hello, I'm a NextJS newbie and I'm having trouble figuring out how to disable the trailing slash on just one page of my NextJS application. Can anyone help me with this? ...

How can I align two inner boxes vertically in the most efficient manner?

.dd{ height:100px; width:100%; border:1px soild red; background:#000; } .dd .d1{ height:20px; width:20px; border:1px solid green; display:inline-block; } .dd .d2{ height:20px; width:20px; border:1px solid green; display:inl ...

The state will remain unchanged until there is an external trigger

Currently, I am utilizing useEffect in order to execute a function that retrieves data from Firebase. Even though the data retrieval works fine, there seems to be an issue with the setState function not updating until after another state has been changed. ...

Styling TD with CSS for bottom border

Is there a way to adjust the bottom border of a TD element in CSS? The image provided demonstrates the desired effect, but with a slight overhang. I need the border to align perfectly with the width of the blue cell above it. This is the code snippet I am ...

Display One Div at a Time in Sequence on Page Load Using jQuery

I have come across this question multiple times: How to Fade In images on page load using JavaScript one after the other? Fade in divs sequentially Using jQuery .fadeIn() on page load? Despite trying various recommended methods, I'm still unable t ...

Scrolling horizontally with scrollbar functionality

My goal is to create a webpage with a horizontally scrollable DIV element in the center, where the scrollbar appears only at the bottom of the DIV, not at the bottom of the entire page. I am wondering if it is possible to have a scrollbar placed at the ve ...

Mastering the Art of Utilizing $(this) in jQuery

$(".item_listing").hover(function(){ $(".overlay_items").display(); },function(){ $(".overlay_items").hide(); } ); This is my jQuery code. I am trying to display the "overlay_items" div when the "item_listing" div is hovered ov ...

Best method for retrieving information from a string

Exploring different techniques to extract data from a string is a common practice, including methods like substring and split. Is there an optimal approach to accomplish this task? For instance, when faced with a URL structure such as http://myServer:8000/ ...

Internet Explorer 9 is not fully extending the width of the box for multiple select options

I am facing an issue with a multiple select input in Internet Explorer 9. The options are not utilizing the full width of the select box, despite having a min-width set on the select element. In Chrome and Firefox, the items fill up the available width pe ...

Upon triggering a GET request to the URL "http://localhost:3000/search", a "404 (Not Found)" error response was received. Interestingly

Can Someone assist me please? I'm having trouble creating a website similar to YouTube and encountering the following error: GET http://localhost:3000/search 404 (Not Found) Uncaught (in promise) Error: Request failed with status code 404 at createEr ...

Enhanced Fancybox Version 2 adjusts iframe width to fit content

I have been attempting to adjust the width of the iframe in fancybox v2 to fit my content properly. However, every time I try, the content appears too large within the iframe and requires horizontal scrolling to view it all. My goal is to see the entire wi ...

Issue with the dimensions and proportions of the canvas

After creating a canvas with HTML and setting the ratio to 16/9 in the CSS, I specified a width of 100vw and added a border. However, I noticed that the canvas appeared larger than expected on the screen. #canvas{ width: 100vw; aspect-ratio: 16/9; border: ...

Listening to React events on multiple elements in an array

When my React render function is running, it ends up rendering a group of elements: data.map((element) => { return <Object onChange={this.onObjectChange} />; }); I'm wondering, what is the best approach to determine which specific object ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Column-oriented and Slim-fit packaging

I have been working on designing a layout with a fixed height that will display multiple columns of specified size to accommodate flowing text. While I have successfully implemented this, I am facing an issue where the enclosing div does not adjust its siz ...

What is the best way to retrieve the id from a SelectField in material-ui with React?

I have exhausted all resources and attempted the solutions provided by others, but unfortunately I am unable to make it work. The issue at hand is that event.target.id and event.target.value are not functioning in this scenario. I have conducted some resea ...

What could be causing the error message "setShowModal is undefined" to appear in my React project?

Here is the code snippet I am working on: import React, { useState } from "react"; import Modal from "./Modal"; function displayModal() { setShowModal(true); } export default function NewPostComponent() { const [showModal, setShowMod ...

Creating a multi-dimensional array using information from a database

I have a unique challenge where I am utilizing a template that generates a menu with a specific structure. In my database, I have various menus stored and I've successfully retrieved them. However, the issue arises when I need to figure out a way to d ...

What is the best way to achieve a smooth rotation effect ranging from 1° to 359° using HTML/CSS in conjunction with JavaScript

Currently, I am retrieving rotation data from a sensor and transmitting it to a webpage containing a 2D-Model that rotates based on this data. To ensure a smoother motion, I have incorporated a CSS transition. However, an issue arises when the rotation da ...