Search code examples
cssscalecenterscaling

Scaling a centered image with window size


img.logo {
    height: auto;
    width: auto\9; /* ie8 */
    left: 50%;
    margin-top: -250px;
    margin-left: -134px;
    position: absolute;
    top: 50%;
    resize: both;

That's the code I'm using. It's a combination of resizing and centering, and yet it's only centering for some reason. I need the image to scale because, as it is currently, it's overlapping with an upper element of the page at very small browser sizes.


Solution

  • You can try using CSS media queries. Basically we define breakpoints based on screen width/browser width, and adjust the image widths accordingly.

    img {
        width: auto;
        height: auto;
    }
    @media all and (max-width: 600px) {
        img { width: 500px; }
    }
    @media all and (max-width: 500px) {
        img { width: 400px; }
    }
    @media all and (max-width: 400px) {
        img { width: 300px; }
    }
    @media all and (max-width: 300px) {
        img { width: 200px; }
    }
    @media all and (max-width: 200px) {
        img { width: 100px; }
    }
    

    See this example

    Hope this can suit your needs

    EDIT: You could even combine the above suggestion with transform: translateX(-50%) translateY(-50%); to keep the image centered at all times. For instance:

    img {
        position: absolute;
        left: 50%;
        top: 50%;
        width: auto;
        height: auto;
        -webkit-transform: translateX(-50%) translateY(-50%);
        transform: translateX(-50%) translateY(-50%);
    }
    @media all and (max-width: 600px) {
        ...
    }
    ...
    

    Here's an example