在图像上对齐长文本

时间:2016-03-13 17:46:28

标签: html css css3

我有一个图像和长文本,应该在图像上正确对齐。我给了图像和文本的id然后在CSS中我使用position-absolute,top和left的文本。一切都很合适,但是当我恢复浏览器时,文本并没有保持原来的位置。当我使用其他位置的文本时,它不会出现在Image上。

<img id="homeimg" src="images/1.jpg" alt="img" width="1280">


                    <p id="text">
                            In 2050, we are projected to have 9 billion on this planet. These people will eat and drink just like we do..
                        requiring a doubling of food production. But food and water security already are the largest challenges for a

                                           thriving global population...and long text

                        </p>

Css编码

#text {
    position: relative;
    text-align: center;
    width: 45em;
    word-wrap: break-word;
    font-size: 25px;
    left: 150px;
    top: 600px;
    font-family: "Trebuchet MS";
    z-index: 100;
}
#homeimg{
    width:100%
}

2 个答案:

答案 0 :(得分:0)

你需要有一个包含元素,一个div,你可以将图像设置为背景。

<div class="container"> 
    <img src="" /> 
    <p class="text">the text</p> 
</div> 

.container { position relative; width:1280px; height:640px; background:url('image.jpg');background-size:cover;} 
.container .text {position:absolute;etc...}

或者,如果您需要内嵌图像,请使用包含position:relative的包含元素 - 内部的任何绝对定位元素都将相对于容器。

<div class="container"> 
    <img src="" /> 
    <p>text...</p> 
</div> 

答案 1 :(得分:0)

通过使用position:relative,文本将相对于其原始位置放置,因此不会粘贴到图像上。问题的一个解决方案是将文本和图像放在容器中,将容器的位置设置为position:relative,然后在图像上使用position:absolute

#container{
  position:relative;
}
#text {
    position: absolute;
    text-align: center;
    width: 45em;
    word-wrap: break-word;
    font-size: 25px;
    left: 150px;
    top: 200px;
    font-family: "Trebuchet MS";
    z-index: 100;
}
#homeimg{
    width:100%
}
<div id=container>
<img id="homeimg" src="http://placehold.it/1280x1000" alt="img">
<p id="text">
                            In 2050, we are projected to have 9 billion on this planet. These people will eat and drink just like we do..
                        requiring a doubling of food production. But food and water security already are the largest challenges for a

                                           thriving global population...and long text
</p>
</div>

jsfiddle

通过这样做,文本将绝对位于容器中。