【问题标题】:How to center text over an image如何让文字在图片上居中
【发布时间】:2023-02-01 14:20:18
【问题描述】:

我试图将图像上方的文本块水平和垂直居中。我查看了其他帖子,但它们似乎无法解决我的问题。

这是代码:

<body>
   <div id="top-of-page">
     <img src="images/etudes.png">
     <div id="text-block">
       <h1>Title</h1>
     </div>
   </div>

#haut-de-page {
  position: relative;
  margin: 10px;
}

#top-of-page img {
  width: 100%;
}

#text-block {
  position: absolute;
  top: 5px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, .5);
  color: white;
  padding-top: 20px;
  padding-left: 20px;
}

即使我设置了 div“文本块”位置:绝对文本仍然出现在图像下方。

你有想法吗?

【问题讨论】:

    标签: html css


    【解决方案1】:

    尝试这个:

    HTML:

    <div id="top-of-page">
        <div class="image">
            <img src="images/etudes.png">
            <div id="text-block">
                <h1>Title</h1>
            </div>
        </div>
    </div>
    

    CSS:

    .image{
        position: relative;
    }
    
    #text-block{
        position: absolute;
        top: 50%;
        left: 50%;
        margin-right: -50%;
        transform: translate(-50%, -50%);
        justify-content: center;
        align-items: center;
        z-index: 100;
        margin: 0 auto;
        background-color: rgba(0, 0, 0, .5);
        color: white;
    }
    

    【讨论】:

    • 谢谢,这是有效的。我只是有一些问题:转换是做什么的:translate(-50%, -50%);对齐项目:居中;和 z-index:100;我不是很确定吗?
    • Align items center 将 div 中的元素居中,因此在本例中为文本。我可能不需要在代码中使用它,我正在尝试一些东西,但转换:translate(-50%, -50%);将它水平居中在中间,Z-Index 是您定位的 div 层。页面上的所有内容都默认设置为 Z-Index: 0;但是如果你将它设置为 Z-Index: 100,它将显示在 Z-Index: 100 以下的所有内容之上;。你甚至可以做 Z-Index:1;但我只做 100 以防万一。
    • 我在这里为您提供了一个很好的资源,它更好地解释了w3.org/Style/Examples/007/center.en.html
    • 请编辑CSS部分。我现在无法编辑它,因为编辑队列已满。
    【解决方案2】:

    根据我从您的问题中了解到的情况,您希望将文本在图像上方垂直和水平居中。 只需使用 margin-left 进行水平居中,使用 margin-top 进行垂直居中。

    #haut-de-page {
        position: relative;
        margin: 10px;
    }
    
    #top-of-page img {
        width: 100%;
    }
    
    #text-block {
        position: absolute;
        top: 5px;
        margin-left: 689px; /* This will center it horizontally */
        margin-top: 489px; /* This will center it vertically */
        background-color: rgba(0, 0, 0, .5);
        color: white;
        padding-top: 20px;
        padding-left: 20px;
        text-align: center;
    }
    

    这将使您的文本在图像顶部垂直和水平居中。

    【讨论】:

    • 我已经编辑了我的代码,但它没有将文本置于图像顶部的中心。 + 为什么选择 689px 和 489px 作为边距?
    • 我不知道为什么它对你不起作用,它对我来说非常有效。我选择 689px 和 489px 没有特别的原因,它以这种方式对我来说是居中的,你可以将它更改为任何你想要的,但这种方式对我来说看起来非常居中。
    猜你喜欢
    • 1970-01-01
    • 2023-01-27
    • 2017-10-09
    • 2016-08-05
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多