How do I center an image if it's wider than its container?

Viewed 41337

Normally, you center images with display: block; margin: auto, but if the image is larger than the container, it overflows to the right. How do I make it overflow to the both sides equally? The width of the container is fixed and known. The width of the image is unknown.

10 Answers

I see this is an old post, so maybe everybody knows this by now, but I needed help for this and I solved it using flex:

.parent {
   display: flex;
   /* give it the width and height you like */

}

.parent img {
   min-width: 100%;
   min-height: 100%;
   object-fit: cover;
}

I found this to be a more elegant solution, without flex, similar to something above, but more generalized (applies on both vertical and horizontal):

.wrapper {
    overflow: hidden;
}
.wrapper img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /* height: 100%; */ /* optional */
}
Related