Having difficulty adjusting the padding of the Material UI table

I have been using the Table component provided by the material-ui library in my React project. However, I have encountered an issue where each row, including the header, has a padding of 24px on the top and bottom that I am unable to modify or overwrite. Despite attempting to adjust the styles of all underlying components, I have not been successful in resolving this issue. Below is the code snippet that illustrates the structure:

<Table>
    <TableHeader adjustForCheckbox={false} displaySelectAll={false} fixedHeader={true}>
        <TableRow>
            <TableHeaderColumn>id</TableHeaderColumn>
            <TableHeaderColumn>name</TableHeaderColumn>
            <TableHeaderColumn>number</TableHeaderColumn>
        </TableRow>
    </TableHeader>
    <TableBody showRowHover={true} displayRowCheckbox={false}>
        {data.map(item => {
            return (
                <TableRow key={item.id}>
                    <TableRowColumn>{item.id}</TableRowColumn>
                    <TableRowColumn>{item.name}</TableRowColumn>
                    <TableRowColumn>{item.number}</TableRowColumn>
                </TableRow>
            );
        })}
    </TableBody>
</Table>

Can anyone suggest which specific component's style should be modified to override this unwanted padding?

Answer №1

To handle these types of requirements, you can use overrides in Material UI like shown in the example below:

Step 1: Add the necessary dependencies

import { ThemeProvider } from '@material-ui/core'
import { createMuiTheme } from '@material-ui/core/styles';

Step 2: Implement custom CSS changes as follows

const theme = createMuiTheme({
    overrides: {
        MuiTableCell: {
            root: {
                padding: '4px 8px',
                backgroundColor: "#eaeaea",
            },
        },
    },
});

Step 3: Wrap your component or code block with

<ThemeProvider theme={theme}>
    <Table>
        <TableRow>
             <TableCell component="td" scope="row">
             </TableCell>
        </TableRow>
    </Table>
</ThemeProvider>

This is how you can override Material UI styles with your own custom styles. Happy Coding :)

Answer №2

The problem stemmed from the height attribute of the TableRow and TableHeaderColumn/TableRowColumn. Strangely, this attribute appeared as padding-top/bottom.

In summary, adjust the height attribute for both the row and columns.

Answer №3

In Material UI table, you have the option to customize size and padding using props.

    import {Table} from '@material-ui/core';
    
    <Table size="small" aria-label="a dense table"></Table>

For more information, check out: https://material-ui.com/api/table/

Ensure that the elements within the table row are styled with small sizes.

Answer №4

It appears that there is a padding added to the Table component, which can be found in the code of that component here.

The padding cannot be changed using the material-ui API, as the context Theme variable desktopGutter is utilized in multiple places. It is recommended not to alter it.

However, you can customize it by adding a custom CSS rule that will be included with your other CSS stylesheets or using "react style" with Radium or a similar tool.

For instance:

<Table id="mytable">...your material-ui JSX...</Table>

In your CSS file:

#mytable .table {
    padding: 0 !important;
}

Correction: This applies to the main table component, not the rows. You can apply a similar technique to override styles for other components by inspecting the CSS paths using developer tools.

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 inability to place a div that is 30% wide alongside another div that is 70% wide, and keep them in a horizontal line?

If I make a div that is 30% wide, and another div that is 70% wide, they do not align horizontally. To fix this, I need to ensure that the combined widths of the two divs are less than 100%. Here's an example of how it can be done: <div id="wrapp ...

Steps for displaying a loader after refreshing data using queryClient.invalidateQueries:1. Utilize the query

I am currently working on a project where I need to redirect to a specific page after updating an item. While the code is functioning correctly, I have encountered an issue with the loader not displaying. export const useUpdateStatusArchiveSurvey = () => ...

Tips for adjusting the border-bottom line in real-time as text is selected from a dropdown menu

$('#select').on('change', function() { name = $('#select :selected').val(); //some code here }); . bdr-txtline { border-bottom: 1px solid black; } <div class="container"> <div class="row"> <div ...

Minimize the number of HTTP requests by including CSS and JS files in PHP

I've been considering a method to reduce the number of HTTP requests made when loading a page by minimizing the amount of downloaded files, while still keeping separate files on the server. The thought process is as follows: <!DOCTYPE html> &l ...

Tips for switching the irregular polygon shape image on click and hoverIf you want to change

I'm looking to create a unique menu with an irregular shape in Adobe Illustrator. I've attempted the following code: <div class="body_container"> <img src="img/sitio_Web.png" alt="" usemap="#sitio_Web_Map" height="787" bor ...

Products failing to appear in shopping cart

I'm facing an issue with my React Redux Cart setup where items are added to the cart state using the addItem action, but they do not appear on the Cart page. Challenge: After adding items to the cart through the addItem action, I can see the state u ...

Banner with video background (not taking up the entire page)

I'm currently working on a website project that involves using a YouTube video as the banner, but I'm facing some challenges in making it work correctly. So far, this is what I have: #video-background { position: absolute; right: 0; top:1 ...

stuck with an outdated dependency causing issues with create-react-app

Encountering a problem with create-react-app failing due to react-scripts expecting an older version of a dependency, making it difficult to select the new version as suggested. This appears to be an interface issue. Interestingly, I can successfully inst ...

The SVG animation is reversing and decreasing in size from the bottom

Feeling lost, I spent a day searching without success. I have a project in full Vuejs and I thought using Svg would be easy and fun, but I can't figure out why the image resizes when playing an animation. The bottom of the svg seems to resize and get ...

You have attempted to make an invalid hook call in the react chat app. Hooks can only be called within the body of a function component

Encountering problems like manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. **Important Error Message/User Notification:** react-dom.development.js:20085 The above error occurred in the <WithStyles(ForwardRef(AppBar))> component: Arrange ...

`Finding the appropriate place to define a variable within a React Component`

When attempting to declare the variable images within the component, I encountered an error. See the screenshot for more information: here. ...

Locate the closing anchor tag following the image

I need to locate the closing anchor tag that wraps an image with the class name "cat-image" in order to move a div right after it. However, I am unable to modify the HTML by adding IDs or classes to the anchor or image tags. Below is an example of the HTM ...

Issues with cookies are preventing functionality when accessing a developmental version of a Next application on a mobile device

During testing of my Next JS development build on a mobile phone, I accessed it using a private IP address (192.XXX.X.24:3000) rather than localhost:3000 on my development machine. The pages load correctly, but when attempting to send cookies back to the b ...

Is the useNavigate() function failing to work consistently?

Currently facing an issue while working on a MERN Web App. When logging in with an existing account, the backend API call returns user properties and a JWT Token. Upon saving it, I use the navigate function to redirect the User to the homepage. Everything ...

Dealing with Unreliable Data in Scatter Plots using React and HighCharts

Initially, I utilized line charts for my data visualization needs. However, I now require multiple data points on the same X-Axis with tooltips, which has led me to discover HighCharts behavior: "In a line chart, by default, Highcharts will display t ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

Creating an alarm clock with customizable time and date formats using ReactJS with Material-UI integration

Here is the code I have written: const date = new Date(); const currentTime = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`; const getDay = `${date.getDay()} ${date.getMonth()} ${date.getDate()}`; return ( <Box> < ...

Relocate the form element from its current position inside the form, and insert it into a different div

I have a sidebar on my website with a search/filter form. I am attempting to relocate one of the elements (a sort order dropdown) from this form, outside the form using CSS/JS and display it inside a div on the right side. Is it possible to do this without ...

I am encountering difficulty in printing multiple documents from FireStore

I am facing an issue where I can successfully retrieve and print all documents from a Firestore collection one by one using console.log(). However, when attempting to display these documents on the screen, only the most recent document is showing up. Here ...

I am eager to develop my React application, however, I encountered an issue with the error message "TypeError: MiniCssExtractPlugin is not a constructor

Error in webpack configuration file: MiniCssExtractPlugin is not recognized as a constructor. This error occurred at line 664 in the webpack configuration file located at D:\React JS Projects\React Facts\reactfacts\node_modules\rea ...