0

I have create the desired effect in a not-so-elegant way using absolute positioning, however this is not very good for re-usability. Is there any way I can instead put these two items in a flex container together but somehow center only the text? Also I am using an MUI icon and it appears to have an invisible square around it that pushes it out of line and am not sure how to fix that as well.

Example

Note I am using React and MUI but this seems to be more of a CSS question so it shouldn't matter too much:

export default function CreateGuest() {
  const defaultText = 'Enter a display name'
  const [guestDisplayName, setGuestDisplayName] = useState(defaultText)
  return (
    <Box
      display="flex"
      justifyContent="center"
      margin="auto"
      sx={{
        width: 366,
        height: 386,
        backgroundColor: 'primary.contrastText',
        boxShadow: '0 2px 3px #00000053',
      }}
    >
      <Stack justifyContent="space-evenly">
        <Typography
          variant="h3"
          component="pre"
          textAlign="center"
          sx={{ position: 'relative' }}
        >
          <ChevronLeftIcon
            sx={{
              fontSize: 48,
              color: 'secondary.main',
              position: 'absolute',
              bottom: '43%',
              right: '87%',
              '&:hover': {
                cursor: 'pointer',
              },
            }}
          />
          {`Create a\nGuest User`}
        </Typography>
        <TextField
          label={guestDisplayName === '' ? defaultText : guestDisplayName}
          onChange={(e) => setGuestDisplayName(e.target.value)}
          variant="outlined"
          color="info"
        ></TextField>
        <Button variant="contained">Create Guest</Button>
      </Stack>
    </Box>
  )
}
Brenden Baio
  • 107
  • 8
  • `align-self` and/or `justify-self` – tacoshy Jul 07 '23 at 23:09
  • 1
    Probably the best approach here is to center the text and then place the icon in a `::before` attribute that is positioned in relation to the text. Then they will always stick together. – ralph.m Jul 07 '23 at 23:31
  • What's the purpose of the icon? It seems... superfluous. – Andy Jul 07 '23 at 23:38

1 Answers1

1

The purpose of flex-box is to set rules how all the elements and text nodes inside it are positioned relative to each other. That means if you want the "Create a guest user" text node to be unaffected you will have to use position absolute to remove it from the normal flow of the document.

Good news is if you set css rules for spacing that prevent the text node and ChevronLeftIcon it shouldn't pose too much of a problem. My advice is, figure out how far down the text starts and set the top and left properties in pixels instead of bottom and right in %. To prevent overlap you could set some kind of padding on the parent ( <= better option ) or a max-width on the text node, provided you wrap it in an element.

Blye
  • 619
  • 4
  • 20