Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<title>Width based on height</title>
<style>
  #grandparent {
    /* Needed for position:absolute in #container */
    position: relative;
  }
  #container {
    /* Match height of #grandparent and
    shrink wrap to width of widest child,
    which will be the img here. */
    position: absolute;
    top: 0;
    bottom: 0;
    /* Don't cover up the alphabet in #sibling */
    left: 1.4em;
    /* Irrelevant styling so you can see the
    container. */
    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: 16px;
  }
</style>
<div id="grandparent">
  <div id="sibling">
    <!-- This text determines the height of
         #grandparent -->
    A<br>B<br>C<br>D<br>E<br>F<br>G<br>H<br>I<br>
    J<br>K<br>L<br>M<br>N<br>O<br>P<br>Q<br>R<br>
    S<br>T<br>U<br>V<br>W<br>X<br>Y<br>Z
  </div>
  <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 < 82; i++)
          document.write("text ");
      </script>
    </div>
  </div>
</div>
Output

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

Dismiss x
public
Bin info
johnmellorpro
0viewers