Html 通过 CSS 在图像上水平居中文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9209764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Horizontal centering text over image via CSS
提问by Zaur Nasibov
Consider the following html:
考虑以下 html:
<div class="image">
<img src="sample.png"/>
<div class="text">
Text of variable length
</div>
</div>
Where:
在哪里:
.image {
position:relative;
text-align:center; // doesn't work as desired :(
}
.text {
position:absolute;
top:30px;
}
Can you please tell, if there is a way to horizontally align the text in the center of the .image
div? I can't use the left
property, since the length of the text is unknown and the text-align
property doesn't work for the .text
div :(
你能告诉我,是否有办法在.image
div的中心水平对齐文本?我无法使用该left
属性,因为文本的长度未知,并且该text-align
属性不适用于.text
div :(
Thank you.
谢谢你。
回答by Damir Kotoric
Try the following CSS:
尝试以下 CSS:
.image {
position:relative;
}
.text {
left: 0;
position:absolute;
text-align:center;
top: 30px;
width: 100%
}
回答by Purnima Sh
Try this:
尝试这个:
.image {
position:relative;
}
.text {
width:100%;
height:100%;
position: absolute;
top: 0;
left: 0px;
justify-content: center;
flex-direction: column;
align-items: center;
display: flex;
}
回答by David says reinstate Monica
First you need to float the .image
element, in order to 'collapse' its block-level descendants to the width of the element, and then use text-align
on the .text
element:
首先,您需要浮动.image
元素,以便将其块级后代“折叠”到元素的宽度,然后text-align
在.text
元素上使用:
.image {
float: left;
}
.text {
text-align: center;
}
Or you could simply give it a display: inline-block
, which will allow it to have its block-level contents contained, and remain in the document flow:
或者您可以简单地给它一个display: inline-block
,这将允许它包含其块级内容,并保留在文档流中:
.image {
display: inline-block;
}
.text {
text-align: center;
}
回答by CSharpened
Can you not use the image as the background image of the 'image' div using background-image: url('/yourUrl/'); and then rather than have your text in its own div simply place it in the image div and then apply text-align: center;
你能不能使用 background-image: url('/yourUrl/'); 将图像用作“图像”div 的背景图像吗?然后,而不是将您的文本放在自己的 div 中,只需将它放在图像 div 中,然后应用 text-align: center;