Home > database >  Make Text Not Overflow in CSS, Material-UI and React
Make Text Not Overflow in CSS, Material-UI and React

Time:09-28

I have here a problem that the cardTitle shouldn't overlap the Card when the texts is too long. Right now what I'm doing is setting a static maxWidth which I don't like. I want it to adjust based on the Card. Is that possible?

CLICK HERE

<Stack
  sx={{
    maxWidth: "330px"
  }}
>
  <Tooltip
    title={<Typography variant="body1">{cardTitle}</Typography>}
  >
    <Typography
      variant="h3"
      sx={{
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
        width: "100%"
      }}
    >
      {cardTitle}
    </Typography>
  </Tooltip>
</Stack>

CodePudding user response:

You need to add overflow: "hidden" to the sx prop of your Stack and its child div's that define the flex-box. Simply, after removing the maxWidth:

sx={{
  maxWidth: "330px"
}}

You need to replace the following part:

<Stack
  gap={2}
  sx={{
    p: 2,
    flexDirection: "row",
    "& > div": {
      "&:first-of-type": {
        flex: "1 1 35%"
      },
      "&:last-of-type": {
        flex: "1 1 65%"
      }
    }
  }}
>

with this code:

<Stack
  gap={2}
  sx={{
    p: 2,
    flexDirection: "row",
    overflow: "hidden",
    "& > div": {
      "&:first-of-type": {
        flex: "1 1 35%",
        overflow: "hidden"
      },
      "&:last-of-type": {
        flex: "1 1 65%",
        overflow: "hidden"
      }
    }
  }}
>

You can take a look at this sandbox for a live working example.

  • Related