Center Oversized Image in Div

Css

Css Problem Overview


I have been trying to sort out how to center an oversized image within a div using css only.

We are using a fluid layout, so the width of the image containers varies as the page width does (height of div is fixed). The image sits within a div, withvalue an inset boxshadow so as to appear as if you are looking through the page at the image.

The image itself has been sized to fill the surrounding div at its widest possible value (the design has a max-width value).

It is pretty easy to do if the image is smaller than the surrounding div:

margin-left: auto;
margin-right: auto;
display: block;	

But when the image is larger than the div it simply starts at the left edge and is off center to the right (we are using overflow: hidden).

We could assign a width=100%, but browsers do a lousy job of resizing images and the web design centers around high quality imagery.

Any ideas on centering the image so that overflow:hidden cuts off both edges evenly?

Css Solutions


Solution 1 - Css

Try something like this. This should center any huge element in the middle vertically and horizontally with respect to its parent no matter both of their sizes.

.parent {
    position: relative;
    overflow: hidden;
    //optionally set height and width, it will depend on the rest of the styling used
}

.child {
    position: absolute;
    top: -9999px;
    bottom: -9999px;
    left: -9999px;
    right: -9999px;
    margin: auto;
    
}

Solution 2 - Css

This is an old Q, but a modern solution without flexbox or position absolute works like this.

margin-left: 50%;
transform: translateX(-50%);

.outer {
  border: 1px solid green;
  margin: 20px auto;
  width: 20%;
  padding: 10px 0;
  /*   overflow: hidden; */
}

.inner {
  width: 150%;
  background-color: gold;
  /* Set left edge of inner element to 50% of the parent element */
  margin-left: 50%; 
  /* Move to the left by 50% of own width */
  transform: translateX(-50%); 
}

<div class="outer">
  <div class="inner">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quos exercitationem error nemo amet cum quia eaque alias nihil, similique laboriosam enim expedita fugit neque earum et esse ad, dolores sapiente sit cumque vero odit! Ullam corrupti iure eum similique magnam voluptatum ipsam. Maxime ad cumque ut atque suscipit enim quidem. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Excepturi impedit esse modi, porro quibusdam voluptate dolores molestias, sit dolorum veritatis laudantium rem, labore et nobis ratione. Ipsum, aliquid totam repellendus non fugiat id magni voluptate, doloribus tenetur illo mollitia. Voluptatum.</div>
</div>

So why does it work?
At first glance it seems that we shift 50% to the right and then 50% to the left again. That would result in zero shift, so what?
But the 50% are not the same, because context is important. If you use relative units, a margin will be calculated as percentage of the width of the parent element, while the transform will be 50% relative to the same element.

We have this situation before we add the CSS

       +---------------------------+
       | Parent element P of E     |
       |                           |
       +-----------------------------------------+
       | Element E                               |
       +-----------------------------------------+
       |                           |
       +---------------------------+

With the added style margin-left: 50% we have

       +---------------------------+
       | Parent element P of E     |
       |                           |
       |             +-----------------------------------------+
       |             | Element E                               |
       |             +-----------------------------------------+
       |             |             |
       +-------------|-------------+
       |>>>>> a >>>>>|
           
       a is 50% width of P

And the transform: translateX(-50%) shifts back to the left

       +---------------------------+
       | Parent element P of E     |
       |                           |
+-----------------------------------------+
| Element E         |                     |
+-----------------------------------------+
|<<<<<<<<< b <<<<<<<|              |
       |            |              |
       +------------|--------------+
       |>>>>> a >>>>|
           
       a is 50% width of P
       b is 50% width of E

Unfortunately this does only work for horizontal centering as the margin percentage calculation is always relative to the width. I.e. not only margin-left and margin-right, but also margin-top and margin-bottom are calculated with respect to width.

Browser compatibility should be no problem: https://caniuse.com/#feat=transforms2d

Solution 3 - Css

Put a large div inside the div, center that, and the center the image inside that div.

This centers it horizontally:

HTML:

<div class="imageContainer">
  <div class="imageCenterer">
    <img src="http://placekitten.com/200/200" />
  </div>
</div>

CSS:

.imageContainer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  position: relative;
}
.imageCenterer {
  width: 1000px;
  position: absolute;
  left: 50%;
  top: 0;
  margin-left: -500px;
}
.imageCenterer img {
  display: block;
  margin: 0 auto;
}

Demo: http://jsfiddle.net/Guffa/L9BnL/

To center it vertically also, you can use the same for the inner div, but you would need the height of the image to place it absolutely inside it.

Solution 4 - Css

Late to the game, but I found this method is extremely intuitive. https://codepen.io/adamchenwei/pen/BRNxJr

CSS

.imageContainer {
  border: 1px black solid;

  width: 450px;
  height: 200px;
  overflow: hidden;
}
.imageHolder {
  border: 1px red dotted;

  height: 100%;
  display:flex;
  align-items: center;
}
.imageItself {
  height: auto;
  width: 100%;
  align-self: center;
  
}

HTML

<div class="imageContainer">
  <div class="imageHolder">
    <img class="imageItself" src="http://www.fiorieconfetti.com/sites/default/files/styles/product_thumbnail__300x360_/public/fiore_viola%20-%202.jpg" />
  </div>
</div>

Solution 5 - Css

i'm a huge fan of making an image the background of a div/node -- then you can just use the background-position: center attribute to center it regardless of screen size

Solution 6 - Css

Do not use fixed or an explicit width or height to the image tag. Instead, code it:

      max-width:100%;
      max-height:100%;

ex: http://jsfiddle.net/xwrvxser/1/

Solution 7 - Css

It's simple with some flex and overflow set to hidden.

enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        div {
            height: 150px;
            width: 150px;
            border: 2px solid red;
        
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>
<body>
    <div>
        <img src="sun.jpg" alt="">
    </div>
</body>
</html>

Solution 8 - Css

One option you can use is object-fit: cover it behaves a bit like background-size: cover. More on object-fit.

ignore all the JS below, that's just for the demo.

The key here is that you need to set the image inside a wrapper and give it the following properties.

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

I've created a demo below where you change the height / width of the wrapper and see in play. The image will always be vertically and horizontally centered. It will take up 100% of its parent width and height, and will not be stretched / squashed. This means that the aspect ratio of the image is maintained. The changes are applied by zooming in / out instead.

The only downside to object-fit is that it doesn't work on IE11.

// for demo only
const wrapper = document.querySelector('.wrapper');
const button = document.querySelector('button');
const widthInput = document.querySelector('.width-input');
const heightInput = document.querySelector('.height-input');


const resizeWrapper = () => {
  wrapper.style.width = widthInput.value + "px";
  wrapper.style.height = heightInput.value + "px";
}

button.addEventListener("click", resizeWrapper);

.wrapper {
  overflow: hidden;
  max-width: 100%;
  margin-bottom: 2em;
  border: 1px solid red;
}

.wrapper img {
  display: block;
  height: 100%;
  width: 100%;
  object-fit: cover;
}

<div class="wrapper">
  <img src="https://i.imgur.com/DrzMS8i.png">
</div>


<!-- demo only -->
<lable for="width">
  Width: <input name="width" class='width-input'>
</lable>
<lable for="height">
  height: <input name="height" class='height-input'>
</lable>
<button>change size!</button>

Solution 9 - Css

Building on @yunzen's great answer:

I'm guessing many people searching for this topic are trying use a large image as a "hero" background image, for example on a homepage. In this case, they would often want text to appear over the image and to have it scale down well on mobile devices.

Here is the perfect CSS for such a background image (use it on the <img> tag):

/* Set left edge of inner element to 50% of the parent element */
margin-left: 50%;

/* Move to the left by 50% of own width */
transform: translateX(-50%);

/* Scale image...(101% - instead of 100% - avoids possible 1px white border on left of image due to rounding error */
width: 101%;

/* ...but don't scale it too small on mobile devices - adjust this as needed */
min-width: 1086px;

/* allow content below image to appear on top of image */
position: absolute;
z-index: -1;

/* OPTIONAL - try with/without based on your needs */
top: 0;

/* OPTIONAL - use if your outer element containing the img has "text-align: center" */
left: 0;

Solution 10 - Css

The width and height are only for example:

parentDiv{
    width: 100px;
    height: 100px;
    position:relative; 
}
innerDiv{
    width: 200px;
    height: 200px;
    position:absolute; 
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

It has to work for you if the left and top of your parent div are not the very top and left of the window of your screen. It works for me.

Solution 11 - Css

I found this to be a more elegant solution, without flex:

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

Solution 12 - Css

based on @Guffa answer
because I lost more than 2 hours to center a very wide image,
for me with a image dimendion of 2500x100px and viewport 1600x1200 or Full HD 1900x1200 works centered like that:

 .imageContainer {
  height: 100px;
  overflow: hidden;
  position: relative;
 }
 .imageCenter {
  width: auto;
  position: absolute;
  left: -10%;
  top: 0;
  margin-left: -500px;
 }
.imageCenter img {
 display: block;
 margin: 0 auto;
 }

I Hope this helps others to finish faster the task :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomView Question on Stackoverflow
Solution 1 - CsshyounisView Answer on Stackoverflow
Solution 2 - CssyunzenView Answer on Stackoverflow
Solution 3 - CssGuffaView Answer on Stackoverflow
Solution 4 - CssEzeeweiView Answer on Stackoverflow
Solution 5 - CssShain LafazanView Answer on Stackoverflow
Solution 6 - Cssleatherjacket4View Answer on Stackoverflow
Solution 7 - CssDino CajicView Answer on Stackoverflow
Solution 8 - CssvoltView Answer on Stackoverflow
Solution 9 - CssDave KooView Answer on Stackoverflow
Solution 10 - CssПанайот ТолевView Answer on Stackoverflow
Solution 11 - CssCezar D.View Answer on Stackoverflow
Solution 12 - CssCristiC777View Answer on Stackoverflow