Search code examples
htmlcssimagecentering

CSS - centered image over a DIV with responsive background and full height image display


If you reed carefully this question you'll note IT'S NOT A DUPLICATED QUESTION. This one is about an image over a responsive background with full height image display. The answers related to the other questions are useless here. Thanks to jacob for his simple solution.

The issue:

I have a DIV with a responsive background. I'm trying to place a centered png "logo" over the DIV (or the background, if you prefer). That's what I have:

.divWithBG {
    background-image: url(...);
    background-size: contain;
    background-repeat: no-repeat;
    width: 100%;
    height: 0;
    padding-top: 45.45%; /* (h/w) x 100 */
    margin-bottom: 30px;
}
.divWithBG img{
    display: block;
    margin: 0 auto;
}

¿What I need to do to place the image inside the div? Centered both, vertically and horizontally.

Many thanks in advance.


Solution

  • You could just make it simpler and use 2 background images. Multiple background images in CSS:

        .divWithBG {
            background-image: url("http://lorempizza.com/380/240") , url("http://lorempizza.com/2000/2000");
            background-size: 50%, contain;
            background-repeat: no-repeat, no-repeat;
            background-position:center;
            width: 100%;
            padding-top: 45.45%; /* (h/w) x 100 */
            margin-bottom: 30px;
        }
    <div class="divWithBG"></div>

    The background image you want to be on top comes first in the background property.