Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

javascript - Scale a div to fit in window but preserve aspect ratio

How can I scale a div to fit inside the browser view port but preserve the aspect ratio of the div. How can I do this using CSS and/or JQuery?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need javascript for this. You can use pure CSS.

A padding-top percentage is interpreted relative to the containing block width. Combine it with position: absolute on a child element, and you can put pretty much anything in a box that retains its aspect ratio.

HTML:

<div class="aspectwrapper">
  <div class="content">
  </div>
</div>

CSS:

.aspectwrapper {
  display: inline-block; /* shrink to fit */
  width: 100%;           /* whatever width you like */
  position: relative;    /* so .content can use position: absolute */
}
.aspectwrapper::after {
  padding-top: 56.25%; /* percentage of containing block _width_ */
  display: block;
  content: '';
}
.content {
  position: absolute;
  top: 0; bottom: 0; right: 0; left: 0;  /* follow the parent's edges */
  outline: thin dashed green;            /* just so you can see the box */
}

The display: inline-block leaves a little extra space below the bottom edge of the .aspectwrapper box, so another element below it won't run flush against it. Using display: block will get rid of it.

Thanks to this post for the tip!


Another approach relies on the fact that browsers respect an image's aspect ratio when you resize only its width or height. (I'll let google generate a 16x9 transparent image for demonstration purposes, but in practice you would use your own static image.)

HTML:

<div class="aspectwrapper">
  <img class="aspectspacer" src="http://chart.googleapis.com/chart?cht=p3&chs=160x90" />
  <div class="content">
  </div>
</div>

CSS:

.aspectwrapper {
  width: 100%;
  position: relative;
}
.aspectspacer {
  width: 100%; /* let the enlarged image height push .aspectwrapper's bottom edge */
}
.content {
  position: absolute;
  top: 0; bottom: 0; right: 0; left: 0;
  outline: thin dashed green;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...