简体   繁体   中英

How to crop an image to fit the required height in the screen?

I have a large image whose height is bigger than the screen height. I have no problem with the width. I need to crop it so that the top 65% of the screen contains this image.

<body>
<img class="img" src="image.jpg" alt="img">
<p>Description</p>
</body>

If I write a CSS as below, the whole image gets compressed to fit in 65% screen. Moreover, if I resize the screen, the image automatically starts attempting to fit in the top 65%, making the whole screen look disturbed.

body, html { height:100% }
img.img { height:65% }

I want instead, the image to be cropped so that the leftover fits in the 65%, and then it stays that way. That is, if I now resize the window, let the vertical scrollbar appear. How can I achieve this?

(PS: I didn't want to give a fixed height because I want the webpage to be viewed in different devices like mobile phone and iPads too.

I think this is what I need:

  1. Get the maximum height of the device (not the current height of the browser screen as the user might have minimized it for some reason)
  2. Crop the image in such a way that it fits the top 65%, and display it
  3. Keep the image size that way irrespective of the user changing the screen size

But I am not sure how to achieve it.)

Is this what you are seeking: http://jsfiddle.net/JjwMw/1/

body, html {
    height: 100%;
    margin: 0;
    padding: 0;
}

.container {
    height: 65%;
    width: 100%;
    position: relative;
    top: -22.75%; /* 65*35/100 */
    background-image: url(http://placehold.it/1024x768);
    background-size: cover;
    background-position: center bottom;
}

Note that the image is now a background-image and is leveraging the background-size property which is not supported in IE8 (...who cares?). If the image cannot be a background image, you scale a div proportionally to fill the width using a padding hack ( Proportionally scale a div with CSS based on max-width (similar to img scaling) ) and have the inside image set to 100% width and height.

Maybe this can be useful to you: http://demo.solemone.de/overflow-image-with-vertical-centering-for-responsive-web-design/

Also a search for css cliping property here or in google should bring enough info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM