Home > other >  How do I fill and center an image uinsg CSS?
How do I fill and center an image uinsg CSS?

Time:09-21

I have an image of arbitrary shape and size which I want to enlarge into a containing div without changing its proportions and without cutting off part of the image.

Below is a diagram of what I have in mind:

enter image description here

enter image description here

Note that the image is sometimes centred vertically, and sometime horizontally.

If the image is always wide, I can use:

img {
    width: 100%;
    height: auto;
    margin: auto;
}

but that won’t work if the image is narrower, as it will end up chopping off the top & bottom.

Is there a way, possibly using grid or flex, which will accommodate the image?

CodePudding user response:

Use object-fit: contain for the img selector in the css,

  • your <img> tag will be your gray frame like in above.
  • the real picture will be hosted as you wish no matter what the intrinsic size of the image is and the size of the <img> tag is.

CodePudding user response:

you don't need use flex/grid , maybe just add object-fit:cover

img {
        width: 100%;
        height: auto;
        margin: auto;
        object-fit:cover;
    }
  • Related