質問

So I was playing with aspect ratio to learn from some mistake I made before and ran into somekind of headache.

In my code the w/h ratio of my div is kept based on the height of my div (could be width but picked height) however due to the width being %, the size of my div is based on the height and width of the window it open in.

What I'd like to do is being able to keep the ratio based on height % but to not have the width distorted depending on the size of the window.

I understand that to do so I shouldn't use % based solutions, however I can't seem to find a unit or way that could do it without screwing up the div size.

Any idea on how I should proceed ?

Here is the code :http://jsfiddle.net/L9Srn/

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

html,body {
    width: 100%;
    height: 100%;
}
#container {
    background: red;
    width: 26.25%;
    height: 72.3%;
    margin-left: auto ;
    margin-right: auto ;
}
(function( $ratio ) {
  $.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 );      

$(function(){
    $('#container').keepRatio('height');
});
役に立ちましたか?

解決

http://jsfiddle.net/L9Srn/4/show/

Take a look:http://jsfiddle.net/L9Srn/4/

var box= $('#container'),
    ratio= 0.363,
    height= 200;

box.height(height).width(height*ratio);

I think all you need to understand is that in css 100% means usually parent's dimensions. And is subjective and can change..And yet there is no way to select what that % represents.

他のヒント

You can do this using CSS only if you wish

DEMO http://jsfiddle.net/kevinPHPkevin/5tzk3/307/

.wrapper:after {
    padding-top: 100%; /*Sets ratio*/
    display: block;
    content: '';
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top