-1

I have a container with some "background" text. I want to center an image in this container and over the text. NOT the text over the image.

The effect I'm looking to reproduce is as below where the shoe is over the Desrupt(?) text.

enter image description here

However, I am not able to center the image in the container. I have created THIS PEN to show what I have.

How do I create a similar effect as per the demo image? Ideally, the image of the penguin should be 75% the width of its container and the "What is lorem" text should be able to be positioned in the container with e.g. margin-top at 20% (so that the text is more readable rather than be completely hidden behind the image) without affecting the position of the image.

My 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;
}
heyred
  • 2,031
  • 8
  • 44
  • 89

1 Answers1

4

You could do this:

.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;
}

The left and top attributes move the image so that its top left corner is at the center of the container, then the transform shifts it back up by half of the image's height, and left by half of its width.

As for the text positioning, just give it margin-top: 20%, and you don't need a margin-bottom attribute.

markmoxx
  • 1,492
  • 1
  • 11
  • 21
  • I updated and saved the Pen with the suggested solution. The image is now centered as wanted, but relative to the text. If I reduce the margin-top of the text to e.g. 20%, the image moves with it and the penguins head disappears. – heyred Feb 01 '19 at 13:47
  • You need to give your `image-over-text` container some height, at the moment its only as high as its contents (not including the image, as that is absolutely positioned). Try adding `height:100%` to your `image-over-text` container. – markmoxx Feb 01 '19 at 14:01