<分区>
<分区>
我有一个组件 (Container
),它包含一个图标(下面用 X
标记)、一个标题和一个子组件(Message
>) 包含一条长消息。我希望 Container 的
宽度环绕图标和标题,这样两者在窗口宽度允许的范围内都在一行上。
消息组件有一个按钮,用于切换长文本的显示。此文本不应拉伸(stretch)父 Container
,并且应与标题的宽度对齐。消息内容可以随时拆分和换行:
我使用了 flex-grow: 1; width: 0;
按照建议在 Message
中的虚拟 div
上设置样式
here以防止它生长。这适用于除 MS Edge 之外的所有浏览器,其中消息内容延伸了父级:
如何在 MS Edge 上解决这个问题? 是否有仅使用 CSS 的替代方法可以防止消息内容拉伸(stretch)其父级?
样式.css:
.box {
display: table;
margin: auto;
border: 1px solid black;
}
.container {
display: flex;
justify-content: center;
}
.icon {
margin-right: 10px;
}
.message {
display: flex;
}
.message > div {
flex-grow: 1;
width: 0;
word-break: break-all;
}
Container.jsx:
export const Container = () => {
return (
<div className='box'>
<div className='container'>
<div className='icon'>
X
</div>
<div className='content'>
<div className='title'>
Some title
</div>
<Message>
Long message that should not make parent wider
</Message>
</div>
</div>
</div>
);
}
Message.jsx:
export const Message = ({children}) => {
const [isExpanded, setExpanded] = React.useState(false);
const handleClick = () => setExpanded(!isExpanded);
return (
<div>
<div>
<button onClick={handleClick}>Click</button>
</div>
{isExpanded &&
<div className='message'>
<div>{children}</div>
</div>
}
</div>
);
}
最佳答案
在消息容器上尝试 width:0;min-width:100%;
:
.box {
display: table;
margin: auto;
border: 1px solid black;
}
.container {
display: flex;
justify-content: center;
}
.icon {
margin-right: 10px;
}
message {
display:block;
width:0;
min-width:100%;
}
<div class='box'>
<div class='container'>
<div class='icon'>
X
</div>
<div class='content'>
<div class='title'>
Some title
</div>
<message>
<div>Long message that should not make parent wider</div>
</message>
</div>
</div>
</div>
或者到消息里面的div:
.box {
display: table;
margin: auto;
border: 1px solid black;
}
.container {
display: flex;
justify-content: center;
}
.icon {
margin-right: 10px;
}
message {
display:block;
}
message > div {
width:0;
min-width:100%;
}
<div class='box'>
<div class='container'>
<div class='icon'>
X
</div>
<div class='content'>
<div class='title'>
Some title
</div>
<message>
<div>Long message that should not make parent wider</div>
</message>
</div>
</div>
</div>
关于css - 如何防止 child 的内容拉伸(stretch) parent 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57599369/
相关文章:
javascript - 为什么 ReactCSSTransitionGroup 会生成多个组件,而我只希望生成一个组件?
image - RN图像调整大小模式: 'contain' strange behaviour
html - 在 flex 容器中用链接包围 img 会导致 img 忽略容器边界
css - 对表 : how to alternate row colors with two or more columns 使用 DIV
javascript - Storybook 插件文档 MDX 不适用于 Edge
reactjs - React - refs - 音频播放 - iOS 上未处理的拒绝(NotSupportedError)