首页 > 解决方案 > Show part of image (unknow width and height) in fixed dimensins 60x60

问题描述

I have a image e.g.,

enter image description here

original dimension of the image is 875 x 583, here I want to show face in seperate div with fixed height,

I know the dimensions for the face

bottom:456
left:277
right:599
top:134

I want to show this part of the image in fixed div 60x60

How can I do that?

right now I can show only the face part using margins

<div class="face-img" style="height: 322px; width: 322px;">
  <img src="https://i.stack.imgur.com/zHXcI.png" style="width: 875px; height: 583px; margin: -134px -599px -456px -277px;">
</div>

but I have to give width and height as original dimensions which are not fixed.

Sample jsfiddle https://jsfiddle.net/new513/8vedg370/4/

I have lot of images like this that I want to show with different dimension, so I'm more of interested in dynamic approach to solve this.

Thanks.

标签: javascriptjqueryhtmlcss

解决方案


horizontal dimension of the face 599 - 277 = 322 final horizontal dimension = 60 horizontal ratio = 322 / 60 = 0.186 final horizontal dimension of the image 875 * 0.186 = 163

vertical dimension of the face 456 - 134 = 322

final vertical dimension = 60

vertical ratio = 322 / 60 = 0.186

final vertical dimension of the image 583 * 0.186 = 108

left position original 277px same ratio as above 0.186 horizontal position 51px

top position original 134px same ratio as above 0.186 vertical position 25px

.box {
 width:60px;
 height:60px;
 background-image: url(https://i.stack.imgur.com/zHXcI.png);
 background-size: 163px 108px;
 background-position: -51px -25px;
 background-repeat: no-repeat;
 border: solid 1px red;
}
<div class="box">

</div>


推荐阅读