Search code examples
cssresponsive-images

Centering oversized image in responsive div


I have been researching this issue for the last few days, and while have found several solutions that work well in static layouts, I am having a problem resolving in responsive design.

We have a series of banner images that we use on our home page, and are trying to get them to appear centered on the image behind text on smaller mobile screens. I can solve this for fixed widths, but we need to make this responsive.

Here is what the current rendition of my CSS code looks like:

#mainSlideshow .item img {
    display: block;
    width: auto !important;
    max-width: none !important;
    height: 350px !important; 
    overflow: hidden;
left: 50%;
-webkit-transform: translateX(-50%);
-moz-transform:  translateX(-50%);
-ms-transform:  translateX(-50%);
-o-transform:  translateX(-50%);
transform:  translateX(-50%);
}
#mainSlideshow .item .carouselImgHold {position: relative; }

The challenge appears to be the movement left - right now, the image just shifts to the left 50% of the img width (no surprise). How do I program the CSS to drift the image only the amount necessary to center the image in the nested div tag?

Many thanks in advance.


Solution

  • You may use text-align and negative margins if IMG stands alone on its line.

    http://codepen.io/anon/pen/PPpYzM

    .oversizedImage {
      text-align: center;
    }
    
    .oversizedImage img {
      margin: 0 -100%;
    }
    /* demo purpose */
    
    .oversizedImage {
      width: 50%;
      margin: auto;
      border: solid;
      box-shadow: 0 0 150px 100px white;/* you should use overflow:hidden; here it only shows how much is outside :) */
    }
    
    .oversizedImage img {
      vertical-align: top;
      /* instead default baseline to avoid gap under */  
      position: relative;
      z-index: -1;
    }
    <div class="oversizedImage">
      <img src="http://lorempixel.com/1200/200"/>
    </div>

    It is only a guess since we miss your HTML