I have a main container
with two child elements
(a text span
and an image svg
) created using the Material UI
component library. My objective is to dynamically adjust the width of the chip based on the length of the text content inside it, while ensuring a minimum sensible width. I also want equal padding on both sides within the chip at all times.
Without specifying a width for the parent container (or setting it as 100% or auto), it expands to fill the entire width of its own parent element, which may be wider than desired for the chip. When I set a fixed pixel width, long text either overflows or gets cut off. How can I make the parent container smartly adjust its width so it fits perfectly around the text content (including necessary padding) without exceeding it?
(The code snippet below is in React utilizing styled-components, but is conceptually similar to HTML/CSS behavior)
const Chip = (props) => (
<StyledChip
label="I'm a chip! I'm a chip!"
clickable={false}
onDelete={() => console.log("Action performed")}
onClick={() => console.log("Another action performed")}
/>
)
const StyledChip = styled(MaterialChip)`
// width: 124px // doesn't work because it doesn't adapt based on child elements
// display: inline-block // doesn't work because the child elements get distorted
// display: inline-flex // child elements no longer distorted, but still takes up full width of container despite no width property
background-color: ${colors.primary200};
color: ${colors.primary800};
font-size: 15px;
font-family: "Work Sans";
padding-left: 14px; // this and the next row specify the consistent padding I desire for the chip
padding-right: 4px;
& .MuiChip-deleteIcon {
color: ${colors.primary800};
margin-left: 8px;
}
& .MuiChip-label {
padding: 0px;
}
&:-moz-focusring {
outline: none;
background-color: ${colors.primary200};
color: inherit;
}
}