【问题标题】:Center image over text in div [duplicate]将图像居中放在 div 中的文本上 [重复]
【发布时间】:2019-06-26 01:54:41
【问题描述】:

我有一个带有一些“背景”文本的容器。 我想在这个容器中和文本上居中一个图像。 不是图片上的文字。

我希望重现的效果如下图所示,鞋子位于 Desrupt(?) 文本上方。

但是,我无法使图像在容器中居中。 我创建了THIS PEN 来展示我所拥有的。

如何根据演示图像创建类似的效果? 理想情况下,企鹅的图像应该是其容器宽度的 75%,并且“什么是 lorem”文本应该能够定位在容器中,例如margin-top 为 20%(使文本更易读,而不是完全隐藏在图像后面),而不影响图像的位置。

我的 CSS

/* Image over text */
.image-over-text {
    position: relative;
    width: 100%;
    height: auto;
}
.image-over-text p {
    color: #000;
    font-size: 4em;
    margin-top: 50%;
    margin-bottom: 50%;
    text-align: center;
    font-weight: 700;
    border: 1px solid green;
}
.image-over-text img {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 75%;
    height: auto;
    border: 1px solid red;
}

【问题讨论】:

    标签: html css


    【解决方案1】:

    你可以这样做:

    .image-over-text img {
        position: absolute;
        left: 50%;                        /* horizontal alignment */
        top: 50%;                         /* vertical alignment */
        transform: translate(-50%, -50%); /* shift the image back to center */
        width: 75%;
        height: auto;
        border: 1px solid red;
    }
    

    lefttop 属性移动图像,使其左上角位于容器的中心,然后transform 将其向后移动图像高度的一半,向左移动一半它的宽度。

    至于文字定位,给margin-top: 20%就行了,不需要margin-bottom属性。

    【讨论】:

    • 我使用建议的解决方案更新并保存了 Pen。图像现在按需要居中,但相对于文本。如果我将文本的页边距减少到例如20%,图像随之移动,企鹅头消失。
    • 你需要给你的image-over-text容器一些高度,目前它只和它的内容一样高(不包括图像,因为它是绝对定位的)。尝试将height:100% 添加到您的image-over-text 容器中。
    猜你喜欢
    • 2017-01-29
    • 2019-11-01
    • 2017-07-04
    • 2019-08-12
    • 2012-12-24
    • 2015-12-05
    • 2015-06-20
    相关资源
    最近更新 更多