Search code examples
cssinternet-explorerpositionscrollbarcss-transforms

image larger than container creates scrollbar on IE and Edge


Background

I need to have an image larger than its container. The idea is to give the users the option to add full-width images to content pages, if they want to.

Problem

I used calc(100vw) with left: 50%; and translateX(-50%). This works perfectly in Chrome and Firefox. However, IE11 and Edge bring a horizontal scroll bar.

Code

HTML

<div>
  <img />
</div>

CSS

div {
    margin: 0 auto;
    width: 400px;
}

img {
    display: block;
    left: 50%;
    position: relative;
    transform: translateX(-50%);
    width: calc(100vw);
}

Fiddle

Here's an example so you can test and play: https://jsfiddle.net/Cthulhu/nbmy5mjf/1/

Question

How can I remove/hide the scroll bar from IE and Edge?

I thought this happened due to the way the image's position is being calculated. However, I noticed that Firefox and Chrome also show a scroll bar if I remove the display: block; from the image. Any ideas?


Solution

  • use

    body {
      overflow: hidden
    }
    

    or just:

    body {
      overflow-x: hidden
    }
    

    and drop the calc() it isn't doing anything there.

    Snippet

    body {
      overflow: hidden
    }
    div {
      border: 5px solid red;
      margin: 0 auto;
      width: 400px;
    }
    img {
      display: block;
      left: 50%;
      position: relative;
      transform: translateX(-50%);
      width: 100vw;
      overflow: hidden
    }
    <div>
      <img src="http://randomrab.com/wp-content/uploads/2015/05/thumpimage.jpg" />
    </div>