Ensure chip component (div) dynamically resizes its width to accommodate varying lengths of child text elements

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;
  }
}

Answer №1

It seems there may be a misunderstanding regarding what you are attempting to achieve, as the default styling for Chip adjusts to the width of the content.

To better illustrate, I have made some modifications based on your styling preferences:

  • I included hardcoded colors since I am not familiar with the contents of your colors object.
  • Some styling adjustments were made to the label (padding, font size).
  • I enhanced the specificity for the outer div's styling (&.MuiChip-root) to ensure it takes precedence over the default styling.
import React from "react";
import Chip from "@material-ui/core/Chip";
import styled from "styled-components";

const StyledChip = styled(Chip)`
  &.MuiChip-root {
    background-color: lightblue;
    color: darkblue;
  }
  & .MuiChip-deleteIcon {
    color: darkblue;
    margin-left: 8px;
  }

  & .MuiChip-label {
    font-size: 15px;
    font-family: "Work Sans";
    padding-left: 14px;
    padding-right: 4px;
  }
`;

const MyChip = props => (
  <StyledChip
    {...props}
    clickable={false}
    onDelete={() => console.log("I did something")}
    onClick={() => console.log("I did something")}
  />
);

export default function Chips() {
  return (
    <div>
      <MyChip label="Hello" />
      <MyChip label="I'm longer than hello" />
    </div>
  );
}

https://codesandbox.io/s/styled-chip-jvegt?fontsize=14

If this solution does not completely address your issue, please provide an updated version in the sandbox illustrating your problem and specifying the desired changes.

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

Is there a way to change my MaterialUI TextField value to uppercase automatically?

Is there a way to make the text entered in a Material UI TextField automatically uppercase? I attempted to use textTransform: "uppercase" in the style attribute, but it doesn't seem to be working. The rest of my component's styling work ...

I am having difficulty modifying the value of 'margin-left' in my SCSS file when using React Bootstrap, even with the '!important' declaration. Can anyone help me understand why this is happening?

Before, I used the 'ml-auto' class in my navbar to make the dropdown align all the way to the left. But now, I want it to stay in place when the screen size shrinks and the navbar switches to vertical orientation. I attempted to apply a specific ...

Transitioning a substantial React application to Next.js specifically to enhance social sharing capabilities and optimize for SEO through server-side rendering

I have successfully built and launched a ReactJS app with separate front and backend (Laravel). One issue I am encountering is the difficulty in sharing pages with dynamic data because React cannot generate meta tags dynamically, resulting in no dynamic p ...

"Utilizing multiple class names in Next.js to enhance website styling

Looking for a way to apply multiple classNames in Next.js, especially when dealing with variable classnames? I'm following the component level CSS approach. Take a look at my code and what I aim to achieve: import styles from "./ColorGroup.mod ...

Creating a table from a PHP associative array

I've been attempting to organize an associative array in ascending order and then display it in an HTML table, but I've hit a roadblock with an error. I tried searching for solutions here on SO and followed the advice provided in some threads: P ...

Performing a map or foreach function on an array of objects limited to the first 5 objects

I need to iterate through an array of objects, but I only want to loop through the first 5 objects and then stop. What is the most efficient way to achieve this? [ {"visibility": 10000,}, {"visibility": 10000,}, {"visibilit ...

Css technique for changing color on mouse hover

I currently have a social media bar on my website with icons for Facebook, Twitter, Google+, and RSS. Here is how it looks: When I hover over the icons, I want the circle around the image to change color to blue. However, every attempt I've made end ...

Question about Selecting Boxes

I'm looking for the name of the HTML tool that is used to create a list of objects from a select field. It typically consists of two boxes with an arrow in between them. For example, when creating a group, Box A would contain a list of users and you c ...

Tips for customizing Material-UI Switch button appearance

Is there a way to remove the box-shadow on the thumb of the Switch button when it's disabled? I've tried various methods like adding the box-shadow in the switchBase and removing it from the thumb, but it affects the parent element as well. Anoth ...

Utilize properties with pseudo-elements in Material UI

import React from "react"; import { Box } from "@material-ui/core"; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles({ box: { '&::before': { content: props => `$ ...

In Angular/Typescript, dynamically add a class to a `td` element when it is clicked. Toggle the class on and off

My problem arises when trying to individually control the arrow icons for each column in my COVID-19 data table. By using Angular methods, I aim to show ascending and descending arrows upon sorting but run into the challenge of changing arrows across all c ...

Troubleshooting Problem with Responsive Bootstrap Navbar

I've been working on creating a menubar using Bootstrap where the logo image is centered instead of being on the left side of the bar. However, I'm facing an issue where the right links in the menu go off the screen. When I view the page with a w ...

Animate CSS during page load

Currently, I am implementing AJAX to dynamically load pages on my website. During the loading process, I wish to incorporate a spinning animation on the logo to indicate that content is being fetched. The jQuery script (although I'm still learning an ...

Is there a way to ensure that the table headers are printed on every page when using Google Chrome

When printing documents in Chrome browser, the table header (thead) does not appear on every page. I want to ensure that the table header is displayed on each printed page, just like it is done with IE and Firefox. However, Chrome does not support this fea ...

Repurpose the identical popup window

I am searching for a solution to use the same pop-up window whenever it is called. Currently, I need to submit a form into a pop-up window and it works well, except in Chrome iOS where each form submission opens a new tab/window instead of reusing the prev ...

What is the best way to create a transparent section within a div to reveal the content below?

My goal is to create a user interface that resembles the design shown in this image https://i.stack.imgur.com/GfiZ8.png One issue I'm facing is how to make the center of the top div circular and transparent, just like in the reference image. I consi ...

Creating visualizations by overlaying shapes onto images using specified coordinates in jQuery

I have a web application in development that integrates with the skybiometry API. Their demo showcases a fantastic user feedback system displayed after facial recognition, similar to the one shown below. I am currently working on implementing a similar fe ...

Error in React + Jest unit test caused by Material-UI typography issue

When I run my React web app in the browser, no warnings are displayed. However, when running unit tests, I am encountering a Material-UI typography error. Warning: Material-UI: you are using the deprecated typography variants that will be removed in the ...

The issue with Next.js is that cookies are not being transmitted along with fetch requests, even when credentials are

I've been developing a Next.js application that originally started as a regular React app created using create-react-app. I'm facing an issue where the cookies are not being sent with my fetch request to the server, despite setting credentials: & ...

What are the dimensions for maximum picture width and height in the Bootstrap 4 grid class col-4? Additionally, can you provide some tips on minimizing image bl

Hey there! I am trying to arrange 3 screenshots in 3 separate columns in one row, resembling steps 1, 2, and 3. I want them all to have the same size. Can you advise on the maximum width and height I should use before they start getting stretched or comp ...