1

A have an image and want to be able to zoom it in/out in a scrollable area with fixed size. This is easy, but if the image is smaller than the scrollable area, it should be centered both vertically and horizontally. I can't find a solution how to align it in the middle vertically. Popular solutions like Vertically align an image inside a div with responsive height or How to vertically center a div for all browsers? do not work because of the scrollable area.

http://jsfiddle.net/smvyadnv/9/

HTML

<div class="outer">
    <div class="inner small">
        <img src="http://lorempixel.com/g/500/300/nature/"></img>
    </div>
</div>
<div class="outer">
    <div class="inner large">
        <img src="http://lorempixel.com/g/500/300/nature/"></img>
    </div>
</div>

CSS

img {
    width: 100%;
}
.outer {
    height: 300px;
    width: 400px;
    overflow: scroll;
    text-align: center;
}
.inner {
    display: inline-block;
}
.inner.small {
    width: 250px;
    height: 150px;
}
.inner.large {
    width: 500px;
    height: 300px;
}
Community
  • 1
  • 1
planky
  • 440
  • 1
  • 4
  • 16

2 Answers2

2

Instead of trying to center the image, you should instead center the .inner element.

You can achieve this using the following vertical / horizontal centering technique (taken from CSS Tricks - Centering in CSS: A Complete Guide):

.outer {
    ...
    position: relative;
    ...
}
.inner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

So your code would look as follows:

img {
    width: 100%;
}
.outer {
    height: 300px;
    width: 400px;
    overflow: scroll;
    position: relative;
}
.inner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.inner.small {
    width: 250px;
    height: 150px;
}
.inner.large {
    width: 500px;
    height: 300px;
}
<div class="outer">
    <div class="inner small">
        <img src="http://lorempixel.com/g/500/300/nature/"></img>
    </div>
</div>
<div class="outer">
    <div class="inner large">
        <img src="http://lorempixel.com/g/500/300/nature/"></img>
    </div>
</div>
planky
  • 440
  • 1
  • 4
  • 16
My Head Hurts
  • 37,315
  • 16
  • 75
  • 117
  • Yes, this is exactly what I want. It works ok in Chrome and FF, but in IE 11, the scroll area behaves strangely. – planky Feb 13 '15 at 12:19
-1

I just gave your inner small image an id called cent(center) and gave it the below css to make it look like it is in the center.

#cent{
   padding-top:50px;
}

Updated fiddle:http://jsfiddle.net/smvyadnv/5/

Let me know if you are looking for something else

m0bi5
  • 8,900
  • 7
  • 33
  • 44
  • Thanks, but the zoom can be dynamic (+/- buttons), so the absolute value of padding will not help. – planky Feb 13 '15 at 07:59