css - 如何仅使用 CSS 基于动态文本设置相等的高度和宽度

标签 css

仅使用 CSS,如果您 <div>Some dynamic text</div> ,如何设置 div 的高度和宽度? width 时尺寸相等由动态文本决定?

最佳答案

您可以将单个段落元素放在 div 中,并使用 calc()p 提供 margin > 考虑到 divwidth(因为 % 总是基于父级的 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 &amp; edit to change div size.</p>
</div>

关于css - 如何仅使用 CSS 基于动态文本设置相等的高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43050098/

相关文章:

javascript - 更改给定数据模型的 HTML 样式

css - 如何使用 css 在文本上添加颜色渐变叠加层?

css - 如何在分页媒体输出的连续页面上设置表格样式?

html - Bootstrap, panel-footer with text align-center horizo​​ntally and vertically jump out 调整大小时

html - 当字符串很小时,col-xs 不起作用

php - text-transform : Capitalize don, t 适用于 <option> 元素

jquery - 按 ID 选中多个复选框

html - ember-bootstrap : page background rendered half gray, 的问题通常应该是全白的

javascript - 为什么部署(串联、缩小)AngularJS + RequireJS 应用程序不起作用?

html - 图像忽略父节点上的最大宽度