仅使用 CSS,如果您 <div>Some dynamic text</div>
,如何设置 div
的高度和宽度? width
时尺寸相等由动态文本决定?
最佳答案
您可以将单个段落元素放在 div
中,并使用 calc()
为 p
提供 margin
> 考虑到 div
的 width
(因为 %
总是基于父级的 width
元素)。
工作示例:
div {
display: inline-block;
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
padding: 6px;
}
p {
margin: calc(50% - 12px) 0; /* half the width minus half the line-height */
font-size: 18px;
line-height: 24px;
}
<div>
<p contenteditable="true">Click me & edit to change div size.</p>
</div>
关于css - 如何仅使用 CSS 基于动态文本设置相等的高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43050098/