Styling Material UI components with CSS is a great way to

I'm facing difficulties while working with Material UI components.

Currently, I have a Material UI table and I want to center-align the text within it.

The standard CSS of Material UI contains an element named MuiTableCell-root-60 which has a text-align property set to left. I am unable to find a way to override this setting as the table does not expose any elements with that specific name. Adding a center align selector directly on the table seems impossible.

Is there a method to customize the default Material UI CSS attributes?

I've attempted various approaches, including adding textAlign: 'center' to the root selector, but it does not seem to take effect.

const styles = theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'auto',
    textAlign: 'center',

  },
  table: {
    minWidth: 700,
  },

});

Answer №1

In the documentation section about Overriding with Classes, you can learn how to customize the behavior of the TableCell's root class.

You can define your classes as mentioned in your question and then apply them to your component using the withStyles function:

import { withStyles } from 'material-ui/styles';

This is a concept known as a Higher Order Component (HOC), which takes a JSS object or a function that returns such an object, adds the styles to the document, and provides a classes prop to the wrapped component:

export default withStyles(styles)(MyComponent);

The classes prop contains an object that links the class names defined in your JSS to the actual class names in the document.

If you want to center the text within a TableCell, you need to override its root class. Define the JSS for this purpose and pass it to `withStyles` so that you have access to a classes prop:

const styles = theme => ({
  centered: {
    textAlign: 'center',    
  },
});

To override the root class when rendering your TableCell, specify a classes prop and provide an object with the overridden classes. In this case, we are focusing on altering the root class:

const SimpleTable = ({ classes }) =>
  <Paper>
    <Table>
      <TableHead>
        <TableRow>
          <TableCell>Dessert (100g serving)</TableCell>
          <TableCell numeric>Protein (g)</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {data.map(n => {
          return (
            <TableRow key={n.id}>
              <TableCell classes={{ root: classes.centered }}>{n.name}</TableCell>
              <TableCell numeric>{n.protein}</TableCell>
            </TableRow>
          );
        })}
      </TableBody>
    </Table>
  </Paper>;

Any attributes specified in the class assigned to root will take precedence.

For a demonstration, check out this codesandbox with a functional example (including the complete code).

Answer №2

If you want to modify the inline styles of the main element, you can adjust the TableRow Properties style as shown below:

 const styles = {
  propContainer: {
    width: '100%',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'auto',
    margin: '0 auto',
  },
};

To learn more, check out this website

Answer №3

One issue you may be encountering is the usage of Material UI syntax for classes.

To properly use classes, follow this format:

<p className={classes.styleName}>

Next, define the const with the corresponding style in your theme:

const styles = theme => ({
  root: {
    width: '100%',
    marginTop: theme.spacing.unit * 3,
    overflowX: 'auto',
  },

  styleName: {
    textAlign: 'center',
    fontSize: '1.6rem',
    fontWeight: '300',
  }
});

This should provide clarity for anyone facing a similar challenge.

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

What is the method to update the switch label in Material UI when the state changes?

I'm exploring the use of Material UI's switch component. My goal is to display the label "Switch is ON" when the switch is toggled on, and "Switch is OFF" when it's toggled off. I'm still learning about managing state in React, so any g ...

Craft an engaging and dynamic Image map with SVG technology to elevate responsiveness and interactivity

I'm currently working on a website and I need to create two clickable sections on the home page. Each section will lead to a different specialization of the company. To achieve this, I decided to use a square image split into two right-angled triangle ...

The React Material UI Autocomplete, when combined with React-window, causes the list to re-render at the top

Looking for some assistance with React since I'm new to it. Having trouble with the Material-ui autocomplete component and need help from experienced React developers. The issue I'm facing is that when I choose an option from the autocomplete dr ...

Containers do not line up properly with each other. Adjusting the width leads to unexpected consequences

As someone who is new to HTML and CSS, I am facing a challenge with aligning the items within a navigation bar on my website. The list serves as a navigation bar and is contained inside the "inner header" div. While I was able to align the entire "nav" con ...

Ways to stop a JS plugin affecting HTML anchors and preventing them from automatically scrolling to the top

My friend is working on a website and he's using a plugin called Flip Lightbox. The basic functionality of the plugin is that when you click on an image, it flips over and pops out as a lightbox. Everything works fine, however, if you scroll down the ...

Can implementing $routeProvider help reduce data usage on a network?

Take a look at this $routeProvider configuration for the navbar and let's assume there is no caching involved app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl : 'pages/home.html& ...

When a JavaScript click event is triggered, IE8 can reset certain margins to zero

I am experiencing an issue with 3 divs containing content that becomes visible when clicking on 3 buttons. You can see a demonstration of the problem here: At times, when I click one of the buttons, the layout seems to be disrupted as shown here: It appe ...

How to use a self-hosted font in a custom Material-UI theme for ReactJS?

Currently, I am in the process of setting up my initial project utilizing Material-UI for ReactJS. My intention is to personalize the default theme by incorporating a custom font (from the server, not sourced from Google Fonts or anything similar). Despite ...

Utilize React.js ThemeProvider to dynamically change themes based on routing

Hey everyone, I have a question regarding changing the theme provider based on the route in my code snippet: const rootElement = document.getElementById('root'); ReactDOM.render( <ThemeProvider theme="MyThemes.default& ...

Changing the text alignment to justify in OWA - HTML emails

Having trouble navigating the Outlook Web App (OWA)? It seems like there are countless issues with different Outlook clients, but OWA is definitely the most poorly documented one. The snippet of code below functions flawlessly in all email clients such as ...

Hey there, I was wondering if it's possible to modify the color of the navbar when scrolling on a specific page

After the first 3 pages with a black background and a transparent navbar with white navigation items, I encounter visibility issues when scrolling to the colorful 4th page. Is there a way to change the navbar color on this specific page using ONLY HTML a ...

Is it beneficial to rotate an image before presenting it?

I am looking for a way to display a landscape image in portrait orientation within a 2-panel view without altering the original file. The challenge I am facing is that the image size is set before rotation, causing spacing issues with DOM elements. Is ther ...

Problematic: BS4 Cards cannot be accommodated within the parent div.Improved: The

Within a dynamic-height parent div, I have two cards stacked on top of each other. However, the issue arises when these two cards do not completely fit inside the parent div. The problem likely stems from the table within the lower card, which is not respo ...

Learn how to set up webpack or Next.js to generate a CSS file from custom Material styles and automatically inject it into the header

One of the things I've done is define some custom material styles, like this: import {createStyles, makeStyles, Theme} from '@material-ui/core/styles'; export const useStyles = makeStyles((theme: Theme) => createStyles({ fab ...

The backface remains visible despite being designated as "hidden"

I have successfully created a "flip card" in CSS3, where the card flips downward to reveal the other side when a user hovers over it. I have ensured that the back face is not visible by setting backface-visibility to hidden. However, despite my efforts, th ...

Modify the location of the input using jQuery

Hey there, I've got this snippet of HTML code: <div class='moves'> <div class='element'><input type='text' value='55' /></div> <input class='top' type='text&apo ...

What is the best method to deallocate and remove the background-color property of CSS once it has been defined?

There is a perplexing issue that I am unable to resolve. The "Shop" section on this page has an intriguing translucent blue-green background: This background is set using the ID "#left-area". Interestingly, on another page, which can be found at , the sam ...

Tips for effectively utilizing the desktopModeMediaQuery feature in the MUI DatePicker

I need help understanding how to utilize the desktopModeMediaQuery feature from material ui. The only relevant link I found was about the Material UI responsive date picker. However, this did not provide specific instructions on how to use desktopModeMed ...

Dynamic Website Layout Bootstrap 4 [ card designs and Tabs ]

Currently, I am in the process of developing a web application that needs to be responsive across various devices including mobiles, tablets, and PCs. My focus right now is on creating a user profile page that adapts well to different screen sizes. To achi ...

Having trouble with the state in ReactJS Material UI?

I'm facing an issue where I want the state of my component to change when I click on a MenuItem. Here's how I'm trying to achieve it: export default class MenuAlumno extends React.Component { constructor() { super(); this.state = { ...