仅使用CSS,如果<div>Some dynamic text</div>
,当动态文本确定div
时,如何确定width
相等尺寸的高度和宽度?
答案 0 :(得分:2)
类似于根据已知宽度设置相等高度,如下所示:https://stackoverflow.com/a/6615994/2479962
首先在容器中包含动态文本,并在动态文本元素上方添加边距推送器(在本例中为:before
):
<div class="container">
<div class="element">
Dimensions set by content.
</div>
</div>
诀窍是将.element:before
的边距基于动态内容font-size
和padding
:
仅限CSS:
.container {
display: inline-block;
position: relative;
background-color: silver;
}
.element {
font-size: 20px;
padding: 10px;
/* So we don't have to take line-height into consideration during calc() */
line-height: 1;
}
.element:before {
content: '';
display: block;
/* 100% is for 1:1 aspect ratio */
/* 20px is taking the contents font-size plus the padding on each side */
margin-top: calc(100% - 20px);
}
根据@ Rounin的建议,我们可以使用:before
和:after
垂直居中,并将计算除以2:
JS Fiddle - Vertically centered
.element:before, .element:after {
content: '';
display: block;
/* 100% is for 1:1 aspect ratio */
/* 10px is taking the contents font-size plus the padding on each side/2 */
margin-top: calc(50% - 10px);
}
答案 1 :(得分:1)
您可以在div
中放置一个段落元素,并使用p
margin
calc()
,width
考虑div
{ {1}}(因为%
始终基于父元素的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;
}
&#13;
<div>
<p contenteditable="true">Click me & edit to change div size.</p>
</div>
&#13;