Severiano
Severiano

Reputation: 1093

how to center image and keep proportions

I have this image that describes what i need, i've tried several things, like

vertical-align: middle;
text-align: center;

I'd like to have the images in theirs original size but centerd, and keep their proporcions.

enter image description here

CSS:

.imgBanner1
{
    max-width: 400px;
    max-height: 233px;
}
.imgBanner2 {
    max-width: 400px;
    max-height: 233px;
}
.imgBanner2:hover {
    opacity: 0.8;
    cursor: pointer;
}
.imgBanner3 {
    width: 190px;
    height: 233px;
}
.imgBanner4 {
    position: relative;
    z-index: -1;
    width: 250px;
    height: 224px;
    margin-top: -4px;
}
.imgBanner5 {
    width: 250px;
    height: 224px;
    margin-top: -4px;
}
.imgBanner6 {
    width: 295px;
    height: 224px;
    margin-top: -4px;
}
.imgBanner7 {
    width: 195px;
    height: 224px;
    margin-top: -4px;
}

I load images using this:

function buildBanner(json) {
    var images = "";

    //total of images in the json object
    var totalImages = 0;
    totalImages = json.length;

    for (var i = 0; i < totalImages; i++) {
        images += "<div class='imgBanner" + (i+1) + "' style='overflow: hidden; display:inline-block; text-align: center;'><img src='" + json[i].img + "' /></div>";
    }
    $("div#receiveBanner").append("<div id='bannerBuilt' style='width: 992px; height: 459px; overflow: hidden'></div>");
    $("div#bannerBuilt").hide().append(images).fadeIn("slow"); 
};

Upvotes: 0

Views: 1251

Answers (1)

Aviv Shaked
Aviv Shaked

Reputation: 762

Instead of using the image tag, you can use the div as the container and use the background-image property to set the image's url. You can then use background-size and background-position:

.imgBanner{
    background-size: contain;
    background-position: center;
}

To set the url, you need to change the code to:

images += "<div class='imgBanner imgBanner" + (i+1) + "' style='overflow: hidden; display:inline-block; text-align: center; background-image: url('" + json[i].img + ");'></div>";

By the way, as you will be using "imgBanner" class for all of them, you can move all of the inline code to css. It easier to maintain.

css:

.imgBanner{
        background-size: contain;
        background-position: center;
        overflow: hidden; 
        display:inline-block; 
        text-align: center;
}

The code will now look like this:

images += "<div class='imgBanner imgBanner" + (i+1) + "' style='background-image: url('" + json[i].img + ");'></div>";

Upvotes: 1

Related Questions