Customizing HTML element tags in MUI: Best practices

Using the most recent version of MUI (v5) and incorporating CssBaseline from @mui/materials. Typically, in CSS, I would set up my styles like this:

body, html, #root {
  width: 100%;
  height: 100%;
  min-height: 100%;
  margin: 0;
  padding: 0;
  font-size: 62.5%; /* This converts rem values for easier calculation */
  text-align: left;
}

MUI Body

(add the following to my theme)

  components: {
    MuiCssBaseline: {
      styleOverrides: {
        body: {
          width: '100%',
          height: '100%',
          minHeight: '100%',
          margin: 0,
          padding: 0,
          fontSize: '62.5%', // This maintains the rem conversion for consistency
          textAlign: 'left'
        }
      }
    }
  }

MUI Root

(add the following to my sxStyle e.g:

sx={{...sxLayout, ...sxLayout.root}}
)

const sxLayout = {
  flexDirection: 'column',
  root: {
    width: '100%',
    height: '100%',
    minHeight: '100%',
    margin: 0,
    padding: 0,
    fontSize: '62.5%', // This ensures consistent rem values
    textAlign: 'left',
    '&': {
      width: '100%',
      height: '100%',
      minHeight: '100%',
      margin: 0,
      padding: 0,
      fontSize: '62.5%', // Maintains the conversion ratio
      textAlign: 'left'
    },
    '&.MuiListItemButton-root': {
      width: '100%',
      height: '100%',
      minHeight: '100%',
      margin: 0,
      padding: 0,
      fontSize: '62.5%', // Keeps the rem conversion intact
      textAlign: 'left'
    }
  }
}

MUI Html

(????)

????

Answer №1

Implementing styles for components can be achieved in various ways. One particularly useful method, especially when working with MUI, is described further down.

For MUI components, many CSS classes are already predefined, making it easy to style components without the need to manually add classes if the <ThemeProvider /> is set up correctly.

Alternatively, you can define regular CSS or SASS in a separate file and import it into your component. Then, apply the defined styles using the className property of the component.

CSS-in-JS is another option where custom CSS can be used via the style property within the JS file of the component:

... //inside your component
const mystyle = {
      color: "white",
      backgroundColor: "DodgerBlue",
      padding: "10px",
      fontFamily: "Arial"
    };
...
    return (
      <div>
      <h1 style={mystyle}>Hello Style!</h1>
      <p>Add some style here!</p>
      </div>
    );

...

The example above is derived from https://www.w3schools.com/react/react_css.asp

This styling approach also works in React without MUI. For MUI-specific customization, the makeStyles() hook is utilized to create custom styles for components. This generates unique class names under the hood while still allowing input through the className property.

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});
export default function MyComponent() {
  const classes = useStyles();
  return <Button className={classes.root}>Hook</Button>;
}

The example above is sourced from

To delve deeper into the functionalities of the makeStyles() hook, refer to the MUI documentation on it: https://mui.com/system/styles/api/#makestyles-styles-options-hook. You can also find information on other related style hooks on the same page by scrolling down.

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

Ensuring that the div remains at the top of the page while scrolling

Although this question has been asked previously, I have searched extensively for something similar to this - Incredible Things You can find what I have at Below is the code snippet: <div id="myElement"> <div id="nav"> <a href= ...

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...

The enclosed component of the withAuthenticator HOC is not receiving any props

Even though I am expecting props.onStateChange, my props object is empty. The props passed to the enclosed component of the withAuthenticator HOC are empty. import { withAuthenticator } from "@aws-amplify/ui-react"; export const App = withAuthenticator(( ...

Unfortunately, I am unable to utilize historical redirection in React

When an axios request is successfully completed, I want to redirect. However, I am encountering an error that looks like this: Below is the code snippet: import React, { useState, Fragment } from "react"; import Sidebar from "../../User/Sid ...

Using Font Awesome Icons within material-ui Buttons

Can anyone help me figure out how to use fontawesome icons in my material-ui Button component? I've been struggling with this issue and could use some guidance. (I am working with React and react-admin framework.) import '../../../node_modules/f ...

Utilizing React to pass parent state to a child component becomes more complex when the parent state is derived from external classes and is subsequently modified. In this scenario,

I'm struggling to find the right way to articulate my issue in the title because it's quite specific to my current situation. Basically, I have two external classes structured like this: class Config { public level: number = 1; //this is a s ...

Dropdown Placement Based on Button Click

Looking to create an interactive dropdown menu with the Alloy UI Dropdown Component that appears when a user clicks on one of four buttons. The goal is for this dropdown to be positioned to the left of the clicked button. var toolsDropdown = new Y.Dropdow ...

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

The attempt to connect with react-native-fetch-blob has not been successful

How do I resolve the issue of displaying a PDF from my assets folder in an Expo, React Native project using react-native-pdf? While scanning folders for symlinks, encountered an error with RNFetchBlob library in my project directory. The automatic linki ...

Is there a method to imitate the background-size "cover" attribute specifically for a div nested within another div using CSS?

Is there a way to have a div inside a div behave like an image with the CSS property background-size:cover? I can't use the image as a background, so I'm looking for a solution that mimics the same behavior. ...

The Ineffectiveness of Social Media Sharing in WordPress

I'm encountering an issue with adding social media sharing buttons to my website's product page. Although I've implemented the PHP code, clicking on the Facebook button only redirects to a page displaying a share button and URL, but it doesn ...

The styles in the CSS file are not behaving as expected

Having an issue with my CSS file for the Header.js module. Despite writing rules, only one style is applying. Can anyone help me identify the problem? Thanks in advance! Header.js component import React from 'react'; import '../../../asset/ ...

Issue with utilizing MUI Select box within React Hook Form's useFieldArray

I am currently working on a personal project and I could really use your expertise. I find myself struggling to tackle issues efficiently, particularly when it comes to performance. I suspect that my difficulties stem from a lack of understanding in certai ...

Having trouble with setting CSS style in <p> tags within Codeigniter framework

Why is the class mentioned in the p tag not applying in Chrome but working in IE and Firefox? <p class="p_error"><?php print $this->validation->errorValue;?></p> Here is the CSS -> .p_error{ color:red; text-align:left; font-size ...

The div "tags" cannot be positioned beneath the photo as it is automatically located alongside the image inside the div

Is there a way to place the "Tags" div beneath an image, creating a bar of tags below it? I've been struggling to position it properly without disrupting the flow of the page. Using absolute positioning is not an option as it would break the layout. A ...

Encountering CORS issue specifically on Safari, yet functioning without any trouble on other

While working on a simple project, I came across an issue specifically with Safari browser. The error message I received was: '[Error] Fetch API cannot load https://randomuser.me/api due to access control checks.' The project is built using Nex ...

What are some ways I can safeguard my CSS from injected elements?

I have created an HTML widget that is inserted into various websites without the use of iframes. However, I am encountering issues where the CSS of some sites is affecting the appearance of my elements, such as text alignment, underlining, and spacing. Is ...

What are the reasons behind the unforeseen outcomes when transferring cookie logic into a function?

While working on my express route for login, I decided to use jwt for authentication and moved the logic into a separate domain by placing it in a function and adjusting my code. However, I encountered an issue where the client side code was unable to read ...

When implementing protected routes in React JS, the this.props.match.params may sometimes appear empty

I am currently working on a React.js app with react-router v5. I am facing an issue where the this.props.match.params is showing up as empty: Object { path: "/", url: "/", params: {}, isExact: false } This is how my App.js looks like: ...

Creating a personalized Material UI theme for enhancing the appearance of a Next.js App Router

Recently transitioned from C# development to diving into Next.js for a client project. Utilizing MUI, I have put in a day of work so far, resulting in a relatively small project. While I grasp the concept of SSR (Server-Side Rendering) theoretically, the ...