【问题标题】:Alignment of long text on image对齐图像上的长文本
【发布时间】:2016-03-14 02:01:55
【问题描述】:

我有一张图片和长文本,应该在图片上正确对齐。我给图像和文本赋予了 id,然后在 CSS 中我使用绝对位置、顶部和左侧的文本。一切正常,但是当我恢复浏览器时,文本不会停留在其原始位置。当我使用其他位置的文本时,它不会出现在图像上。

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

【问题讨论】:

  • 你能用我们能看到的图像做一个小提琴吗?
  • 图像是内联对象。如果你想在图像上定位元素,他们必须有position:absolute,W3school 有一个很好的例子。 w3schools.com/css/css_positioning.asp
  • 您是否尝试过使用您的图片作为 #text 元素的 css 背景图片?

标签: html css


【解决方案1】:

你需要有一个包含元素,比如一个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> 

【讨论】:

    【解决方案2】:

    通过使用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

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

    【讨论】:

    • 对我不起作用。由于使用容器的位置,一切都会受到干扰。
    猜你喜欢
    • 2017-03-15
    • 2012-12-30
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多