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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:24:31  来源:igfitidea点击:

Horizontal centering text over image via CSS

csshtmlimagealignment

提问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 .imagediv? I can't use the leftproperty, since the length of the text is unknown and the text-alignproperty doesn't work for the .textdiv :(

你能告诉我,是否有办法在.imagediv的中心水平对齐文本?我无法使用该left属性,因为文本的长度未知,并且该text-align属性不适用于.textdiv :(

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 .imageelement, in order to 'collapse' its block-level descendants to the width of the element, and then use text-alignon the .textelement:

首先,您需要浮动.image元素,以便将其块级后代“折叠”到元素的宽度,然后text-align.text元素上使用:

.image {
    float: left;
}
.text {
    text-align: center;
}

JS Fiddle demo.

JS小提琴演示

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;
}

JS Fiddle demo.

JS小提琴演示

回答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;