Sagi_Avinash_Varma
Sagi_Avinash_Varma

Reputation: 1509

Clipping a responsive full width image

I have to clip an image which spans full width. The following things didnt work for me

  1. clip: this requires position absolute so the block elements dont stack below
  2. background-position: it doesnt clip properly when zoomed the clipped portion increases when zoom in and vice versa.
  3. wrapper: the wrapper height is dependent on the browser width so its value should be dynamic.

I used js with setinterval 1 millisec. so that wrapper height is constantly updated. works perfect in all scenarios but setinterval is bad practice. so please suggest a cleaner way to implement this.

document.onreadystatechange = setInterval(function () {
  if (document.readyState == "complete") {
    brow_width = document.body.clientWidth;

    var h1 = (brow_width/7);
    document.getElementById("clip1").style.opacity = "1";
    if(brow_width > 700){
    document.getElementById("clip1").style.height= h1;
    }
    else{
    document.getElementById("clip1").style.height= 110;
    }

    var h2 = (brow_width/33.33);    
    document.getElementById("clip2").style.opacity = "1";
    if(brow_width > 700){
    document.getElementById("clip2").style.height= h2;
    document.getElementById("banner2").style.top= h2 - brow_width*0.35;
    }
    else{
    document.getElementById("clip2").style.height= 21;
    document.getElementById("banner2").style.top= -220;
    }   
}
},1);

<!--two different clips of the same image-->
<div id="clip1">
<img id="banner1" src="banner.jpg">
</div>
<div id="clip2">
<img id="banner2" src="banner.jpg">
</div>

Upvotes: 3

Views: 1333

Answers (1)

Nelson Menezes
Nelson Menezes

Reputation: 2094

Try this:

HTML

<div class="banner">
  <div class="bannerImg"></div>
</div>

CSS

.banner {
  position: relative;
  padding-bottom: 15%;
}

.bannerImg {
  background-image: url(...);
  background-size: cover;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

(Also here: http://jsfiddle.net/N6mCw/)

The idea is to use the outer wrapper to crop the image. If you need to support IE<9 then instead of a background image you'll have to add an <img> tag within the inner div and remove the background-image CSS:

<div class="banner">
    <div class="bannerImg">
        <img src"…" />
    </div>
</div>

Although… the best way to do this would be to actually crop the image to the correct aspect ratio beforehand!

Upvotes: 1

Related Questions