居中显示图片上方的文字

8
这里是我的代码概述
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值而改变。因此,标题可能很短,也可能很长,我希望它无论如何都可以居中。

有什么好的想法吗?


你需要将图片放置在 div 的背景中。 - Pranay Bhardwaj
3个回答

13

尝试以下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 查看。


很遗憾,它没有你可能想象的效果:http://d.pr/i/huk4 - Chase Westlye
@ChaseWestlye 嗯,让我试试看,大约需要2分钟。 - Patsy Issa

4

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>


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

我认为你做得很好...文本已居中,但背景图像不再显示: CSS:http://d.pr/i/7hMZ HTML:http://d.pr/i/dzeK 渲染:http://d.pr/i/bCBR有什么想法? - Chase Westlye
高度是动态的,行高200像素不会导致文本居中。 - Patsy Issa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接