简体   繁体   中英

How to clip an image on % of width and % of height

I tried few links but dint get anything fruitful. I am working on this

http://www.w3schools.com/cssref/pr_pos_clip.asp

but in my case I need to clip the image on "%" rather than putting some predefined px values. However I can not do this .

How to achieve that ??

The Clip property doesn't support percentages (yet). To achieve that effect, you can either:

1) Wrap the image in a div, set percentage width and height and overflow: hidden; For example:

<div id="test">
    <img src="https://www.google.com/images/srpr/logo11w.png">
</div>

div#test {
    width: 200px;
    height: 100px;
    overflow: hidden;
}

JSFiddle

2) Instead of the image, use a div with percentage width and height and the image set as a background-image.

3) Use javascript to calculate the required width and height after the image has been rendered and work with that.

If you want to do it in percentages, you can achieve it with an additional extra wrapper div with dimensions same as image.

Try following CSS and HTML.

HTML

<div class="wrapper">
    <div class="imgContainer">
      <!-- NOTE: image dimensions are same as in "wrapper" class-->
      <img src="path/to/img.jpg" width="200" height="140" />
    </div>
</div>

CSS

.wrapper{
    width : 200px;
    height : 140px;
}
/* Below width and height are in percentage w.r.t. those in 
   'wrapper' class whose width and height are same as image.
*/
.imgContainer{
    width : 50%;
    height : 50%;
    overflow : hidden;
}

Check this fiddle .

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