Search code examples
javascriptjqueryhtmlcssscale

Scale div like an image


I am trying to scale content within a div based on it's width.

As an example, I have a div:

<div id="container"></div>

I have styling such as:

#container { margin: 0px auto; width: 810px; height: 800px; border: 1px solid #000; }

This presents me with a div 810px wide and 800px tall, nicely centered on screen with an outline.

Let's say I have a banner graphic at the top which should scale with the div, so I have it's width at 100%. Works great.

I have a background graphic for the container div itself set to scale with the width as well, working great.

What I need help with, is let's say I had a heading underneath the banner, but this font size needed to scale with everything else, based on the width of the container. How would I accomplish this?

I am also looking to add other elements such as buttons, which would need to scale.

At the end of the day, imagine and image with a width of 100%, and how it scales proportionately, perfectly. This is how I need the container div and all its children to act, like an image. I hope this makes sense.

I have looked at scaling text like in this link: http://jsfiddle.net/Aye4h/

This is the perfect behavior, but I need more than just text to scale.


Solution

  • Scaling is a complicated matter as some content is vector based or otherwise rendered on-demand, and some content is raster based (e.g., images). If you want to scale an entire element as if it was just an image, then have a look at transform: scale:

    #scaled {
      border: #f00 solid 5px;
      background: #0ff;
      height: 500px;
      margin: -125px;
      transform: scale(0.5);
      width: 500px;
    }
    <h1>This is outside the scaled element</h1>
    <div id="scaled">
      <h2>Inside the scaled element</h2>
      <p>An image:</p>
      <p><img src="http://i.imgur.com/3A1Loxw.jpg"></p>
    </div>

    Keep in mind that the transform is applied after the image has been laid out on the page so all content around it will think it's still at its original size. You can work around this in many other ways, such as by using negative margin values (as I did in the example).