Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <meta charset="utf-8">
  <title>Responsive dive according to its background image height</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="http://stackoverflow.com/questions/22344308/resize-according-to-its-background-image-height/22344970#22344970">
</head>
<body>
<div class="wrap">
    <div id="main">
    </div>
    <div>another div</div>
</div>
</body>
</html>
 
html,body{
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
.wrap{
  position: relative;
  z-index: auto;
  width: 100%;
  max-width: 960px;
  height: 100%;
  margin: 0 auto;
}
#main{
    width: 100%;
    height: 70%;
    
    background: gold url(http://lorempixel.com/500/300) no-repeat top center;
    background-size: contain;
}
 
var main = $('#main'),
    imgwidth  = 500,
    imgHeight = 300,
    imgRatio  = imgHeight/imgwidth,
    mHeight   = main.height();
$(window).resize(function() {
  var cmWidth  = main.width(),
      cmRatio  = mHeight/cmWidth;
  if (cmRatio >= imgRatio) {
    main.height(imgRatio * cmWidth);
  } else {
    main.height('70%');
  }
}).resize();
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
qolamipro
0viewers