Difference between `.myClass`, `& .myClass`, `&myClass`, (and nesting thereof) syntax in CSS/SASS/SCSS/MUI

Viewed 31

The following code snippet is shown in: https://mui.com/material-ui/react-slider/#music-player

<Slider
  aria-label="time-indicator"
  size="small"
  value={position}
  min={0}
  step={1}
  max={duration}
  onChange={(_, value) => setPosition(value as number)}
  sx={{
      color: theme.palette.mode === 'dark' ? '#fff' : 'rgba(0,0,0,0.87)',
      height: 4,
      '& .MuiSlider-thumb': {
          width: 8,
          height: 8,
          transition: '0.3s cubic-bezier(.47,1.64,.41,.8)',
          '&:before': {
              boxShadow: '0 2px 12px 0 rgba(0,0,0,0.4)',
          },
          '&:hover, &.Mui-focusVisible': {
              boxShadow: `0px 0px 0px 8px ${
                  theme.palette.mode === 'dark'
                    ? 'rgb(255 255 255 / 16%)'
                    : 'rgb(0 0 0 / 16%)'
                }`,
          },
          '&.Mui-active': {
              width: 20,
              height: 20,
          },
      },
      '& .MuiSlider-rail': {
          opacity: 0.28,
      },
  }}
/>

I don't fully grasp this syntax in CSS/SASS/SCSS/MUI (In Bakus-Naur form (https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form)):

<.> | <&.> | <& .>myClass: {value}

As well as the nesting of this syntax:

<.> | <&.> | <& .>myClass: {<.> | <&.> | <& .>myNestedClass>: {value}}

1 Answers

In SCSS the "&" symbol is an alias for ‘parent’ when style rules are nested.

If there is a space between the & and the next class - it means that the nested class is a child of the parent, and if there is no space then it means the nested class is on the parent class.

.abc{ & .xyz { … } }

The above will compile to .abc .xyz{…} which is a descendant selector and will match any element with a class of "xyz" that is a child of an element with the class of "abc".

.abc{&.xyz{…}}

The above Will compile to .abc.xyz{…} which is a class selector and will match to any element with a class of both "abc" and "xyz".

.abc{&:hover{…}}

The above will compile to .abc:hover{...} which is a state pseudo-selector and will match an element with a class of "abc" when it is being hovered on.

Related