我有一个父div
和two child divs
组件库中实现的span
(一个svg
和一个Material UI
)。我的目标是,芯片宽度将根据内部文本的长度(合理的最小宽度)进行调整。我一直希望芯片中的左右填充量相同。
当我未在父div上设置宽度(或宽度为100%或自动)时,它会填满自己的父容器的整个宽度,该宽度比我想要的芯片还要宽。如果我设置了固定的像素宽度,则太长的文本会溢出或被隐藏。我该如何智能地调整此父div,使其仅与文本一样宽(加上必要的填充),而不能比文本宽?
(下面的代码在带有样式组件的React中,但是在语义上与HTML / CSS非常相似,并且在样式和框模型方面都相同)
const Chip = (props) => (
<StyledChip
label="I'm a chip! I'm a chip!"
clickable={false}
onDelete={() => console.log("I did something")}
onClick={() => console.log("I did something")}
/>
)
const StyledChip = styled(MaterialChip)`
// width: 124px // doesn't work because it doesn't adjust 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 define the consistent padding I want on 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;
}
}
答案 0 :(得分:0)
由于默认的Chip
样式会根据内容的宽度进行调整,因此我可能会误解您要实现的目标。
这是一个基于您的样式的示例,但需要进行一些调整:
colors
对象中包含什么,因此我对某些颜色进行了硬编码。&.MuiChip-root
)样式的特异性,以确保它胜过默认样式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>
);
}
如果这不能完全解决您的问题,请提供此沙箱的一个版本,以演示您的问题并描述应该看起来有什么不同。