如何在此图像上显示文本

时间:2015-11-12 20:27:55

标签: html css

如何将文本居中于css中的图像?

这里我附上了代码,我是css的新手

<div class="image">
    <img src="sample.png"/>
    <div class="text">
       <h2>Some text</h2>
    </div>
</div>


<style>
.image {
   position: relative;
}

h2 {
   position: absolute;
   top: 200px;
   left: 0;
   width: 100%;
   margin: 0 auto;
   width: 300px;
   height: 50px;
}
</style>

2 个答案:

答案 0 :(得分:0)

How about something like this:

Its done by using position:absolute and z-index to place the text over the image.

    #container {
      height: 400px;
      width: 400px;
      position: relative;
    }
    #image {
      position: absolute;
      left: 0;
      top: 0;
    }
    #text {
      z-index: 100;
      position: absolute;
      color: white;
      font-size: 24px;
      font-weight: bold;
      left: 150px;
      top: 350px;
    }
    <div id="container">
      <img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />
      <p id="text">
        Hello World!
      </p>
    </div>

答案 1 :(得分:0)

您可以使用以下内容:

JS Fiddle

&#13;
&#13;
.image {
   position: relative;
}

img {
    width: 100%;
    height: 200px;
}

.text {
   position: absolute;
   bottom:0;
   left: 0;
   width: 100%;
}

.text h2 {
    text-align: center;
    color: #FFF;
}
&#13;
<div class="image">
    <img src="https://cdn.photographylife.com/wp-content/uploads/2015/10/Wadi-Rum-5-650x434.jpg" alt="My Image" />
    <div class="text">
       <h2>Some text</h2>
    </div>
</div>
&#13;
&#13;
&#13;