Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<title>Width based on height</title>
<style>
  #container {
    /* Needed for position:absolute later. */
    position: relative;
    /* Shrink wrap to width of widest child,
    which will be the img here. */
    display: inline-block;
    /* Arbitrary input height (adjust this);
    doesn't need to be a fixed value. */
    height: 50vh;
    /* Irrelevant styling so you can see the
    outer block. */
    background: red;
  }
  #container > img {
    /* Adjust this value - this is how wide
    you want #contents to be, as a fraction
    of the height of #container.
    It works because if you only specify the
    height of an image, it's width will be
    set automatically to preserve the aspect
    ratio of the image. In this case the
    ratio is 1:1 so the image will end up
    exactly as wide as it is tall. */
    height: 25%;
    /* Irrelevant styling so you can see the
    image (which is actually transparent). */
    background: pink;
  }
  #contents {
    /* Position this so it exactly matches
    the size of #container */
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    /* Irrelevant styling so you can see
    the size of #contents. */
    outline: 1px solid blue;
    font-size: 14px;
  }
</style>
<div id="container">
  <!-- The img here is a 1x1px transparent gif from: http://stackoverflow.com/questions/6018611/smallest-data-uri-image-possible-for-a-transparent-image -->
  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
  <div id="contents">
    <script>
      for (var i = 0; i < 53; i++)
        document.write("text ");
    </script>
  </div>
</div>
Output

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

Dismiss x
public
Bin info
johnmellorpro
0viewers