Html 在图像上居中文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18735040/
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-29 13:15:11  来源:igfitidea点击:

Centering Text over Image

htmlcssimagetext

提问by Chase Westlye

Here's my summarized code

这是我总结的代码

HTML:

HTML:

<div class="wrap">
      <div>
      <img src="Pictures/titlepic.jpg" width="1035" height="200">
      <h1 class="text_over_image">Welcome to my Sandbox</h1>
      </div>
</div>

CSS:

CSS:

.wrap{
    width: 1060px;
    margin: auto;
    }
.text_over_image{
    position: absolute;
    top: 20px;
    }   

I've tried left: 50%, text-align:center, any number of things with no great luck. I didn't want to do a left: 50px(or whatever the value needs to be) as whats unseen is that the length of the text changes depending on Javascript values. So the title could be short, or long and I want it to center no matter what.

我已经尝试过left: 50%text-align:center任何数量的事情都没有好运气。我不想做left: 50px(或任何需要的值),因为看不见的是文本的长度会根据 Javascript 值而变化。所以标题可能很短,也可能很长,无论如何我都希望它居中。

Ideas?

想法?

回答by Patsy Issa

Try the following css:

试试下面的css:

.text_over_image{
    position: absolute;
    top: 0;
    left:0;
    right:0;
    bottom:0;
 }  

===Edit ===

===编辑===

.wrap {
    width: 1060px;
    height:auto;
    margin: auto;
    text-align:center;
    position:relative;
}
.text_over_image {
    position: absolute;
    margin: auto;
    top: 0;
    left:0;
    right:0;
    bottom:0;
    color:#fff;
    height:100px;
}

There you go JsFiddle

你去吧JsFiddle

回答by sbrbot

div.counter {
    position: relative;
    display: inline-block;
}
div.counter span {
    position: absolute;    
    text-align: center;
    height: 100%;
    width: 100%;
}
div.counter span:before {
   display: inline-block;
   vertical-align: middle;
   height: 100%;
   content: '';
}
<div class="counter">
    <span>TEXT</span>
    <img src="http://placehold.it/100x100"/>
</div>

回答by Sasidharan

HTML

HTML

<div class="wrap">
      <div>
       <h1 class="text_over_image">Welcome to my Sandbox</h1>
      </div>
</div>

CSS

CSS

.wrap
{
background-image:url(Pictures/titlepic.jpg);
width:1035px;
height:200px;
}
.text_over_image
{
text-align:center;
line-height:200px;
}