响应改变div尺寸保持长宽比

当我给一个图像的百分比宽度或高度只有它会增长/收缩保持其纵横比,但是如果我想要与另一个元素相同的效果,是否有可能在一起使用百分比绑在一起的宽度和高度?

你可以使用纯CSS来做到这一点。 没有JavaScript需要。 这利用了(有点违反直觉的)事实,即padding-top百分比是相对于包含块的宽度 。 这是一个例子:

 .wrapper { width: 50%; /* whatever width you want */ display: inline-block; position: relative; } .wrapper:after { padding-top: 56.25%; /* 16:9 ratio */ display: block; content: ''; } .main { position: absolute; top: 0; bottom: 0; right: 0; left: 0; /* fill parent */ background-color: deepskyblue; /* let's see it! */ color: white; } 
 <div class="wrapper"> <div class="main"> This is your div with the specified aspect ratio. </div> </div> 

克里斯的想法,另一个select是使用伪元素,所以你不需要使用绝对定位的内部元素。

 <style> .square { /* width within the parent. can be any percentage. */ width: 100%; } .square:before { content: ""; float: left; /* essentially the aspect ratio. 100% means the div will remain 100% as tall as it is wide, or square in other words. */ padding-bottom: 100%; } /* this is a clearfix. you can use whatever clearfix you usually use, add overflow:hidden to the parent element, or simply float the parent container. */ .square:after { content: ""; display: table; clear: both; } </style> <div class="square"> <h1>Square</h1> <p>This div will maintain its aspect ratio.</p> </div> 

我在这里放了一个演示: http : //codepen.io/tcmulder/pen/iqnDr

 <style> #aspectRatio { position:fixed; left:0px; top:0px; width:60vw; height:40vw; border:1px solid; font-size:10vw; } </style> <body> <div id="aspectRatio">Aspect Ratio?</div> </body> 

这里要注意的关键是vw = viewport width, vh = viewport height

这是我的解决scheme

 <div class="main" style="width: 100%;"> <div class="container"> <div class="sizing"></div> <div class="content"></div> </div> </div> .main { width: 100%; } .container { width: 30%; float: right; position: relative; } .sizing { width: 100%; padding-bottom: 50%; visibility: hidden; } .content { width: 100%; height: 100%; background-color: red; position: absolute; margin-top: -50%; } 

http://jsfiddle.net/aG4Fs/3/

 (function( $ ) { $.fn.keepRatio = function(which) { var $this = $(this); var w = $this.width(); var h = $this.height(); var ratio = w/h; $(window).resize(function() { switch(which) { case 'width': var nh = $this.width() / ratio; $this.css('height', nh + 'px'); break; case 'height': var nw = $this.height() * ratio; $this.css('width', nw + 'px'); break; } }); } })( jQuery ); $(document).ready(function(){ $('#foo').keepRatio('width'); }); 

工作示例: http : //jsfiddle.net/QtftX/1/