Cannot get the input padding override to work in MUI autocomplete

I've been attempting to modify the padding within the MUI autocomplete component, but unfortunately, it doesn't appear to be functioning correctly

const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
    const checkedIcon = <CheckBoxIcon fontSize="small" />;
    const _getCustomOption = (props, option, { selected }) => {
        const renderOption = (
            <li { ...props }>
                <Checkbox icon={ icon } checkedIcon={ checkedIcon } checked={ selected } classes={ { root: classes.checkbox } } />
                    { option }
            </li>
        );
        return multiple? { renderOption } : {};
    };
    const _renderInput = (params) => (
        <Field { ...params } variant="outlined" placeholder={ placeholder } InputProps={ { ...params.InputProps, readOnly: true } } classes={ { root: `${fieldRootClassName} ${classes.textFieldRoot}` } } />
    );

    return (
        <React.Fragment>
            <Typography variant="subtitle1" gutterBottom className={ `${labelClassName} ${disabled ? classes.disabledText : ''}` }
                        noWrap align="left" style={ { color: labelColor } }>
                { required ? `${label} *` : label }
            </Typography>
            <Autocomplete fullWidth multiple
                          classes={ { root: `${fieldRootClassName} ${classes.textFieldRoot}`, inputRoot: `${classes.createEventInput}`, input: `${classes.createEventInput}`, listbox: classes.dropdownListBox, tag: classes.chipTag, paper: classes.dropdownPaper } }
                          disableCloseOnSelect={ multiple } options={ options } renderInput={ _renderInput } disabled={ disabled } onChange={ _onSelectionChange } { ..._getCustomOption } />
        </React.Fragment>
    );

This is the specific class I am attempting to utilize createEventInput

createEventInput: {
   padding: '10.5px 14px 10.5px'
}

Upon opening the application, this is the issue I'm encountering: component styles when inspecting the input element

However, you'll notice that other styles are not being applied as expected: Padding not working properly I understand that using the !important flag would override the input padding, but I prefer to avoid that approach.

Answer №1

The issue you're facing is related to css specificity. The selector responsible for applying the styles is:

.css-eozd4h-MuiAutocomplete-root .MuiOutlinedInput-root .MuiAutocomplete-input
with a css specificity of (0,3,0).

You have also shared an image showing your styles being applied but then overwritten. This occurs because the selector is

.CustomTextField-createEventInput-13685
, which has a specificity of (0,1,0). To ensure that your padding styles are applied correctly, your selector needs to have a higher specificity than (0,3,0).

In the code snippet provided, it's not clear what exactly returns your classes object. Assuming you are using something like makeStyles and still want to apply the input styles through the classes key, you can boost the specificity by employing the following approach:

createEventInput: {
  "&&&&": {
    padding: '10.5px 14px 10.5px'
  }
}

This method works because the & serves as the "parent selector," representing

.CustomTextField-createEventInput-13685
. By repeating the & four times, we generate a final selector of
.CustomTextField-createEventInput-13685.CustomTextField-createEventInput-13685.CustomTextField-createEventInput-13685.CustomTextField-createEventInput-13685
, providing a specificity of (0,4,0) although it may not be visually appealing.

NOTE: Depending on your project setup, matching the specificity might allow your styles to take precedence, potentially needing only three repetitions (&&&).

An alternative, less cumbersome way to match specificity could involve styling the input via the "root":

textFieldRoot: {
  // With a specificity of (0,3,0), this may not suffice if greater specificity is required.
  "& .MuiOutlinedInput-root .MuiAutocomplete-input": {
    padding: '10.5px 14px 10.5px'
  }
}

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

Issue encountered when attempting to locate the file path within the getStaticProps function of an internal page in Next Js

I'm currently implementing a multi-language feature on my Next JS app. Below is the folder structure of my project. https://i.stack.imgur.com/5tD2G.png On the Home page (index page), I successfully retrieved the locales module using getStaticProps: ...

Encountering a Next.js 404 Error while Attempting to Reach a Page

Encountering a 404 error while trying to access a page in my Next.js project despite following guidance from documentation and online resources. The setup is as follows: The structure of my Next.js project is: my-nextjs-project/ app/ profile.js project ...

Tips for adjusting the button spacing on a bootstrap navbar

As someone who doesn't work on front-end tasks frequently, I have encountered an issue while creating a navbar using Bootstrap. The problem arises when trying to add multiple buttons as it causes the spacing between them to appear strange. Does anyon ...

Admin-on-rest: Edit Page - Element Error Detected

When I navigate to the Edit page after clicking the Edit button on the list page in my frontend application using admin-on-rest, I encounter an error that says "INCORRECT ELEMENT". Can anyone help me understand why this is happening? Thank you View image ...

"Exploring the versatility of using variables in jquery's .css

I’m facing an issue where I need the rotation of a div to be based on the value stored in "anVar." This is what I currently have: function something() { $('.class').css('-webkit-transform:rotate('anVar'deg)') } The desi ...

Cannot get the value of the ReactComponent Button to display on my React application

I have developed a React App and my index.js file is structured as follows: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker fr ...

The outline none property on the Material UI IconButton is malfunctioning

Attempting to style with CSS as shown in the following example: <CustomColorIconButton> <DeleteForeverIcon /> </CustomColorIconButton> const CustomColorIconButton = withStyles({ root: { color: "#ff8833", ...

After saving a rich field in Microsoft Sharepoint, I noticed that a new "External Class" was automatically added to my CSS

Although I am new to Sharepoint, I have experience in HTML and CSS. I recently created a mini HTML application that changes the pictures of hyperlinks on hover. It works perfectly when run on a normal browser outside of Sharepoint. However, the issue aris ...

Seeking assistance with installing Node version >14 on Windows 8. Any guidance would be greatly appreciated

Currently running node version 13.14.0, but in order to utilize the latest create-react-app version v5.0.0, I must upgrade to node version 14 or higher. Unfortunately, this is not supported on Windows 8. Any suggestions for a workaround? Encountering an e ...

What could be causing my API requests to my Vercel hosted API to be interpreted as GET rather than POST? Should I be considering any specific authorization requirements?

I set out to develop a personal portfolio website on Vercel with a combination of Python/Flask for the backend and React for the frontend. During the development phase, I managed to establish communication between my front end component and the backend API ...

No buttons found after implementing identical code in a React functional component

Within a TypeScript file for a class component, I have defined the actionTemplate as shown below: // Constructor code: constructor(props: Props) { super(props); this.actionTemplate = this.actionTemplate.bind(this); this.st ...

Issue with Nextjs: Page style fails to load initially leading to oversized icons and broken CSS

I'm experiencing an issue with my page where the icons appear oversized and the CSS seems to be broken upon loading. I followed the official Next.js MUI5 example. "next": "^12.3.1", "react": "^18.2.0", &quo ...

Is there a way to prevent my table from surpassing the width of my card using CSS?

My table inside a card is not responsive on small screens, causing it to go outside the card. I've tried various solutions like using flex on the parent element and setting the table width equal to the card but nothing seems to work. The card should a ...

Issues with ReactJS routing, encountering errors in the 500 range, as well as difficulties with the functionality of .htaccess rewrite rules specifically on

I developed a React application using the create-react-app template. In my package.json file, I set the homepage value to '.' like this: { ... "homepage": ".", ... } However, after deployment, I encountered 500 s ...

Use jQuery to switch back and forth between two different sets of classes

I am attempting to switch between two different sets of classes using jQuery. My goal is to change from one custom icon to a font-awesome icon upon clicking an element. While I have been successful in changing a single class, I am facing challenges when tr ...

The function signature '(event: ChangeEvent<HTMLInputElement>) => void' does not match the expected type 'ChangeEvent<HTMLInputElement>'

This is my first time using TypeScript to work on a project from the ZTM course, which was initially written in JavaScript. I am facing an issue where I am unable to set a type for the event parameter. The error message I receive states: Type '(event: ...

Ensuring the validity of float and non-empty values in JavaScript

Embarking on the journey of web development, I'm delving into basic applications. My current project involves creating a straightforward webpage to add two numbers and implementing preliminary validations - ensuring that the input fields are not left ...

Tips for retrieving hidden columns in a datagrid

Currently, I am utilizing the premium version of material-ui's DataGrid known as x-Grid. This feature enables users to toggle between hiding and showing columns either through the column options menu or the Columns Panel on the toolbar. My objective: ...

Activate Bootstrap modal using an anchor tag that links to a valid external URL as a fallback option

To ensure accessibility for users who may have javascript disabled, we follow a company standard of developing our web pages accordingly. Our target demographic still includes those familiar with VCRs blinking 12:00. One particular challenge involves a te ...

Obtain your access token from auth0

Currently, my setup involves utilizing auth0 and nextJS. My objective is to have the user redirected to the callback API after successfully logging in with their credentials. Here is the snippet of code I am working with: import auth0 from '../. ...