将文本居中放在图像上

时间:2013-09-11 07:22:19

标签: html css image text

这是我的汇总代码

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:

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

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

想法?

3 个答案:

答案 0 :(得分:10)

尝试以下css:

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

===编辑===

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

你去JsFiddle

答案 1 :(得分:4)

&#13;
&#13;
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: '';
}
&#13;
<div class="counter">
    <span>TEXT</span>
    <img src="http://placehold.it/100x100"/>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:3)

<强> HTML

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

<强> CSS

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