The nth-child selector fails to function properly with a customized MUI component in CSS

I've created a styled component as shown below:

const FormBox = styled(Box)(({ theme }) => ({
  width: "47vw",
  height: "25vh",
  backgroundColor: theme.palette.grey[100],
  borderRadius: theme.shape.borderRadius,
  marginLeft: "auto",
  marginRight: "auto",
  marginTop: theme.spacing(5),
  display: "flex",
  justifyContent: "space-between",
  flexWrap: "wrap",
  padding: theme.spacing(2),
  columnGap: theme.spacing(5),
  '&>*': { flex: '0 1 auto' },
  '&:nth-child(4)': { flex: '1 1 200px', backgroundColor: 'red' }, //????????????? 
}));

The issue is that the CSS specified for the 4th child (the button component below) does not apply. Here are the four children inside this styled component:

<FormBox component="form" noValidate autoComplete="off">
      <TextField label="Title">{title}</TextField>
      <TextField label="Amount">{amount}</TextField>
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <DatePicker
          label="Date"
          onChange={(newValue) => {
            setDate(newValue);
          }}
          renderInput={(params) => <TextField {...params} />}
          sx={{ width: 50 }}
        />
      </LocalizationProvider>
      <Button variant="contained" sx={{height: 50}}>Add</Button>
    </FormBox>

Answer №1

The & symbol is a unique selector introduced by SCSS that is used within nested selectors to reference the outer selector.

In the code snippet below, it demonstrates how to select the fourth element with the class name FormBox.

FormBox = {
  "&:nth-child(4)": { // your style here },
}

If you want to target the fourth child element specifically, you should first select all child elements of FormBox using >*, and then specify the fourth child using :nth-child(4).

FormBox = {
  "&><*:nth-child(4)": { // your style here },
}

Alternatively, using &>>:nth-child(4) will yield the same outcome.

Note that the asterisk (*) is optional in simple selectors. For example, *.warning and .warning have the same meaning.MDN

To explore more examples and deepen your understanding, check out these resources:

MDN/CSS_Selectors

w3schools/css_selectors

Answer №2

For a better result, consider using &>*:nth-child(4) rather than &:nth-child(4).

To gain a better understanding of this concept, check out the following resource:

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

Menu changes when hovering

I want to create an effect where hovering over the .hoverarea class will toggle the visibility of .sociallink1, .sociallink2, and so on, with a drover effect. However, my code isn't working as expected. Additionally, an extra margin is automatically ...

What are the steps to decode a JSON response using jQuery?

Working on a fun little web app for my significant other and me to keep track of movies we want to watch together. I'm exploring using TheMovieDatabase.org's API (which only supports JSON) to simplify the process of adding movies to our list. The ...

Why do some button clicks not trigger a page refresh in JavaScript?

Hey there, I have a situation where I have two buttons - one to add a dog to the dog list and another to clear the entire list. Both buttons are functioning properly, but I'm having an issue with only the OnSubmit button refreshing the page. The dog ...

Solving a bug that causes the Select to not display any values can be accomplished by clicking on it and allowing it to retrieve the previous object

UPDATE I encountered an issue where the Select component was not displaying any of the items in the list. Instead, it would only display the last value when clicked on. After some troubleshooting, I found a workaround by using Context to send informatio ...

Searching for different forms of multiple words using regular expressions

I have a value saved in a variable: var myvalue = "hello bye"; var myText = "hellobye is here and hello-bye here and hello.bye" Is there a way to check if different versions of myvalue are present in the text? I am currently using this pattern: hello ...

CSS media query to target specific viewport width

In my JavaScript code, I am dynamically creating a meta viewport. I set the value of this viewport to be 980px using the following script: var customViewPort=document.createElement('meta'); customViewPort.id="viewport"; customViewPort.name = "vie ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { 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, ...

How can I retrieve the height of a dynamically generated div in Angular and pass it to a sibling component?

My setup consists of a single parent component and 2 child components structured as follows: Parent-component.html <child-component-1 [id]="id"></child-component-1> <child-component-2></child-component-2> The child-compo ...

Adding event listeners to elements created dynamically

I am facing an issue with some dynamically generated divs from a JavaScript plugin. The divs have a class .someclass which wraps existing divs. My goal is to add a class to the children of .someclass. I attempted to achieve this by using the following code ...

Organizing a list based on the text within span elements using either jQuery or underscore

I'm a bit confused about how to arrange an unordered list by the content of the span within each list item. Here is my HTML code: <ul id="appsList"> <li><span>aa</span> <span class="sort">androi ...

Can the MUI5 tree view be seamlessly integrated with MUI5 autocomplete?

After successfully creating an MUI5 Tree View complete with checked, unchecked, and indeterminate states, I am now setting my sights on integrating this feature with an MUI5 autocomplete. Can this be achieved? If so, could someone provide guidance on how ...

Tips for sequentially calling multiple await functions within a for loop in Node.js when one await is dependent on the data from another await

I am currently facing a challenge where I need to call multiple awaits within a for loop, which according to the documentation can be performance heavy. I was considering using promise.all() to optimize this process. However, the issue I'm encounterin ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Accessing JavaScript cookie within .htaccess file to establish redirection parameters according to cookie content

Is there a way to modify the rules within my .htaccess file so that it can properly read a user-side cookie and redirect based on its content? The scenario is this: I have a cookie called userstate which contains an abbreviation of US states, such as AL ( ...

When opening the menu, the focus of Material UI input is lost, causing

I am currently working on an input field that should open a menu when it is focused. The issue I am facing is that while the menu opens correctly, the input field loses focus and all of its custom styling when the menu is visible. Does anyone have any sugg ...

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

Access the value of a submitted form using jQuery, when there are multiple forms with identical class names

I've looked for a solution here but couldn't find one that meets my needs. I have multiple forms with the class name .sbt-form: <form class='sbt-form'> <input name='kord' val=1/> </form> <form class= ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

What is the best way to save information from an axios promise into my database on separate lines?

Having a technical issue and seeking assistance: Currently, I am encountering an issue with my axios request to the database. After successfully retrieving the data, I aim to display it in a select form. However, the response is coming back as one continu ...

Updating Angular model remotely without relying solely on the controller

I am struggling to call the addRectangleMethod method from my Javascript code in order to retrieve server-side information into the Angular datamodel. However, I keep encountering an error stating that the method I'm trying to call is undefined. It&ap ...