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

Links in Next.js fail to function properly after deploying on Firebase

I recently deployed my project on Firebase, but I'm encountering an issue with the links not functioning correctly. Everything works fine when tested locally, with paths like /account working as expected. However, after deployment, only /account.html ...

Troubleshooting JavaScript Object allocation problem

As someone who is not an expert in JavaScript, I have a question that may seem silly. Let's say I have the following snippet of HTML: <div> <script type="text/javascript"> var variable_2 = new SomeObject(); </script ...

What is the best location to store a ReactJS file?

As I dive into learning ReactJS Components, here is the code I am working with. Could someone please advise me on where to save this file or which folder I should keep it in? <body> <div id="anmol"></div> <script src="https: ...

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...

Save the retrieved data in a variable and pass the entire JSON object as a prop to a React component

Having some trouble with my code. I need the app to fetch a JSON from an API and pass it as a prop so that each component file can use it and display the element on the screen. The issue is, I can't seem to figure out how to store the fetched informa ...

Steps for inserting new text in front of an element's existing text

Is there a way to insert text before the original content of an element? I know how to add text after using createTextNode, as shown in this example: $("#button").click(function() { $( ".text" ).append( document.createTextNode( " Hello" ) ); }); < ...

Tips for correctly positioning CSS elements:

I am currently working on a slider using noUi Slider and aiming for an elegant solution. To accommodate the large size of the handle, I expanded the base UI with extra values which are not allowed, causing the handle to jump back to the permitted values. T ...

Trouble with setting the color attribute using setProperty in a GXT text area

Help needed in dynamically changing the font color of a text area from the color menu. Existing attempts to change it have not been successful. Can someone provide assistance? final ColorMenu fontColorMenu = new ColorMenu(); fontColorMenu.getPalette().a ...

What is the best way to trigger the scrollTo function after the list (ul) with images has finished reflowing?

In my React application, I used the Material-UI List component to display images with varying dimensions and limited to a max-width of 25%. Upon loading the page, I call scrollTo({top: some-list-top-value}) on the list to position it at a specific point. ...

Is there a tool available for viewing the HTML5 Web SQL database?

Is there a tool available, such as PHPMyAdmin, that allows users to easily view HTML5 Web SQL databases from their web browser? ...

Having difficulty selecting an item from the MaterialUI package

While trying to utilize the MaterialUI Select component with typescript/reactjs, I encountered an issue during the instantiation of the Select element. The error message I'm receiving states: Type 'Courses' is missing the following properti ...

When creating a PDF from HTML using iText, the CSS styling is not applied

Even though I am able to generate a PDF from an HTML string, the issue is that it doesn't apply the CSS styles. How can I create a PDF with CSS styling? Please assist! I have already attempted using CSSResolver. Below is my code snippet: {String res ...

The margins are misaligned on a tablet-sized device due to an issue with the media

Why are the margins not maintained well when media queries are applied for tablet view, i.e., medium-sized devices? The third block is coded to acquire 100% width in medium size but the margins do not align well. What could be causing the third paragraph t ...

Enhance the aesthetics of placeholder text in Semantic UI React using CSS styling

Currently, I am utilizing Semantic UI dropdowns within my React application to generate drop-down menus similar to the ones showcased in their documentation found here: The initial text displayed is "Select Friend", and it appears with a semi-transparent ...

In a responsive design, rearrange a 3-column layout so that the 3rd column is shifted onto or above the

My question is concise and to the point. Despite searching online, I have not been able to find any information on this topic. Currently, my layout consists of 3 columns: ---------------------------- |left|the-main-column|right| ------------------------- ...

Typescript Server Problem: Critical Error - Mark-compacts Inefficiently Close to Heap Limit, Allocation Unsuccessful - JavaScript Heap Exhausted

Whenever I run my CRA project, I consistently encounter this error in my console. It seems to be related to the typescript server. Is there a solution for this issue? 99% done plugins webpack-hot-middlewarewebpack built preview 7c330f0bfd3e44c3a97b in 64 ...

What are the reasons for the various methods available for importing my JS code?

Here is the structure of my folders: --public ----frontend.js --views ----fontend.ejs The frontend.js file is located inside the public folder, while the frontend.ejs file is in the views folder. In my HTML / EJS file, I included the JavaScript (fronten ...

"Troubleshooting: Fixing the issue with jQuery datepicker not

After implementing the jQuery Datepicker on a field, I noticed that even though assigning a value to the field shows in Chrome's developer tools... Unfortunately, the assigned value does not show on the front end. I am aware that we can set a defaul ...

Tips for applying unique scss classes to a div based on a specific condition

Currently, I am developing a chat application where I want to showcase messages from one specific user on the right side of the screen while displaying messages from other users on the left side. <ion-item *ngFor="let message of messages | slice:0: ...

Can you use logical AND in Selenium XPath to combine multiple contains() filters?

My objective is to identify a specific element using Selenium: <a class="ABC" href="#" data-test-id="XXX|YYY|ZZZ"> There are various elements on the page with attributes matching "ABC", "XXX", " ...