dermoritz
dermoritz

Reputation: 12991

CSS for image that give container image size

I have a really simple html (the image is much larger than screen):

  <body>
    <script src="js/panzoom.min.js"></script>
    <script src="js/app.js"></script>
    <div class="parent">
      <div id="image" class="image-container">
        <img class="image" src="/bhBbJt6.jpg" alt="image" />
      </div>
    </div>
  </body>

I want that

Without any CSS the width seems to be always the screen width but the height seems to be image height. To limit body and parent to screen height i added:

body,html {
    margin: 0;
    padding: 0;
    max-height: 100vh;
    overflow: hidden; 
}
.parent {
    max-height: inherit;
 }

With this i have my first 3 points checked (not sure if this could be achieved in a better way, height or max-height: 100% is not working on .parent - don't know why)

But how to give image-container and the image itself the size of the image?

EDIT:

add jsfiddle: https://jsfiddle.net/he0p6q4s/

If you "inspect" the output you'll see that image container has size:

enter image description here

I want the width and height always be same as picture. in this case only width is correct.

Upvotes: 1

Views: 103

Answers (1)

A Haworth
A Haworth

Reputation: 36426

Using the given code an with an image that is roughly 10 times wider than the viewport the img and its image-container both give a width equal to the width of the image i.e. I don't see the problem as described in the question.

The problem may lie in the code being used to find out what the widths are.

If you use element.offsetWidth on either of these elements it returns the width of the viewport (as overflow: hidden is set).

To get the width of the whole img element or its container (ie the scrolled out bits as well) using element.scrollWidth gives the natural width of the img (and similarly for height).

Upvotes: 2

Related Questions