首先在容器中包含动态文本,并在动态文本元素上方添加边距推送器(在本例中为:before):
Dimensions set by content.
诀窍是将.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:
.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);
}