首页 文章

如何在保持图像宽高比的同时拉伸图像以填充<div>?

提问于
浏览
158

我需要将此图像拉伸到可能的最大尺寸,而不会溢出它的图像 .

我无法预测图像的宽高比,因此无法知道是否使用:

<img src="url" style="width: 100%;">

要么

<img src="url" style="height: 100%;">

我不能同时使用两者(即style = "width: 100%; height: 100%;"),因为这会拉伸图像以适合 <div> .

<div> 的大小按屏幕的百分比设置,这也是不可预测的 .

16 回答

  • 5

    2016年更新:

    现代浏览器的表现要好得多 . 您需要做的就是将图像宽度设置为100%(demo

    .container img {
       width: 100%;
    }
    

    因为你不得不使用一些脚本 . 以下是我将如何使用jQuery(demo):

    CSS

    .container {
        width: 40%;
        height: 40%;
        background: #444;
        margin: 0 auto;
    }
    .container img.wide {
        max-width: 100%;
        max-height: 100%;
        height: auto;
    }
    .container img.tall {
        max-height: 100%;
        max-width: 100%;
        width: auto;
    }​
    

    HTML

    <div class="container">
     <img src="http://i48.tinypic.com/wrltuc.jpg" />
    </div>
    

    <div class="container"> <img src="http://i47.tinypic.com/i1bek8.jpg" /> </div>

    脚本

    $(window).load(function(){
     $('.container').find('img').each(function(){
      var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
      $(this).addClass(imgClass);
     })
    })
    
  • 162

    不是一个完美的解决方案,但这个CSS可能有所帮助缩放是使这个代码工作的原因,理论上理论上这个因素对于小图像理想地工作 - 但在大多数情况下,2,4或8工作正常 .

    #myImage {
        zoom: 2;  //increase if you have very small images
    
        display: block;
        margin: auto;
    
        height: auto;
        max-height: 100%;
    
        width: auto;
        max-width: 100%;
    }
    
  • 2

    只使用 CSSHTML 有一种更简单的方法:

    HTML:

    <div class="fill"></div>
    

    CSS:

    .fill {
        overflow: hidden;
        background-size: cover;
        background-position: center;
        background-image: url('path/to/image.jpg');
    }
    

    这会将您的图像作为背景,并将其拉伸以适应 div 尺寸而不会失真 .

  • 6

    如果可以,请使用背景图像并设置 background-size: cover . 这将使背景覆盖整个元素 .

    CSS

    div {
      background-image: url(path/to/your/image.png);
      background-repeat: no-repeat;
      background-position: 50% 50%;
      background-size: cover;
    }
    

    如果你坚持使用内嵌图像,有几个选项 . 首先,有

    object-fit

    此属性作用于与 background-size: cover 类似的图像,视频和其他对象 .

    CSS

    img {
      object-fit: cover;
    }
    

    可悲的是,browser support并不是那么好用IE到版本11根本不支持它 . 下一个选项使用jQuery

    CSS + jQuery

    HTML

    <div>
      <img src="image.png" class="cover-image">
    </div>
    

    CSS

    div {
      height: 8em;
      width: 15em;
    }
    

    自定义jQuery plugin

    (function ($) {
      $.fn.coverImage = function(contain) {
        this.each(function() {
          var $this = $(this),
            src = $this.get(0).src,
            $wrapper = $this.parent();
    
          if (contain) {
            $wrapper.css({
              'background': 'url(' + src + ') 50% 50%/contain no-repeat'
            });
          } else {
            $wrapper.css({
              'background': 'url(' + src + ') 50% 50%/cover no-repeat'
            });
          }
    
          $this.remove();
        });
    
        return this;
      };
    })(jQuery);
    

    像这样使用插件

    jQuery('.cover-image').coverImage();
    

    它将拍摄一张图像,将其设置为图像的包装元素上的背景图像,然后从文档中删除 img 标记 . 最后你可以使用

    Pure CSS

    您可以将其用作后备 . 图像将向上扩展以覆盖其容器,但不会缩小 .

    CSS

    div {
      height: 8em;
      width: 15em;
      overflow: hidden;
    }
    
    div img {
      min-height: 100%;
      min-width: 100%;
      width: auto;
      height: auto;
      max-width: none;
      max-height: none;
      display: block;
      position: relative;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    

    希望这可能对某人有帮助,编码愉快!

  • 3

    感谢CSS3

    img
    {
       object-fit: contain;
    }
    

    https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

    IE和EDGE一如既往的局外人:http://caniuse.com/#feat=object-fit

  • 3

    仅使用HTML和CSS,这是不可能的,或者至少是异国情调和复杂的 . 如果你愿意抛出一些javascript,这里有一个使用jQuery的解决方案:

    $(function() {
        $(window).resize(function() {
            var $i = $('img#image_to_resize');
            var $c = $img.parent();
            var i_ar = $i.width() / $i.height(), c_ar = $c.width() / $c.height();            
            $i.width(i_ar > c_ar ? $c.width() : $c.height() * (i_ar));
        });
        $(window).resize();
    });
    

    这将调整图像的大小,使其始终适合父元素,无论它与 $(window).resize() 事件绑定,当用户调整窗口大小时,图像将会调整 .

    这并不是试图将图像置于容器中心,这是可能的,但我想这不是你所追求的 .

  • 25

    设置外部 container div的宽度和高度 . 然后在img上使用以下样式:

    .container img{
        width:100%;
        height:auto;
        max-height:100%;
    }
    

    这将帮助您保持img的宽高比

  • 1

    我遇到了这个问题,寻找一个类似的问题 . 我正在创建一个响应式设计的网页,页面上放置的元素宽度设置为屏幕宽度的百分比 . 高度设置为vw值 .

    由于我使用PHP和数据库后端添加帖子,纯CSS无法实现 . 然而,我确实发现jQuery / javascript解决方案有点麻烦,所以我提出了一个整洁的(所以我认为自己至少)解决方案 .

    HTML(或php)

    div.imgfill {
      float: left;
      position: relative;
      background-repeat: no-repeat;
      background-position: 50%  50%;
      background-size: cover;
      width: 33.333%;
      height: 18vw;
      border: 1px solid black; /*frame of the image*/
      margin: -1px;
    }
    
    <div class="imgfill" style="background-image:url(source/image.jpg);">
      This might be some info
    </div>
    <div class="imgfill" style="background-image:url(source/image2.jpg);">
      This might be some info
    </div>
    <div class="imgfill" style="background-image:url(source/image3.jpg);">
      This might be some info
    </div>
    

    通过使用style =“”可以让PHP动态更新我的页面,并且CSS样式与style =“”一起将以完美覆盖的图像结束,缩放以覆盖动态div标签 .

  • 66

    使用此方法,您可以使用div和图像的图像变化比率填充div .

    jQuery:

    $(window).load(function(){
       $('body').find(.fillme).each(function(){
          var fillmeval = $(this).width()/$(this).height();
          var imgval = $this.children('img').width()/$this.children('img').height();
          var imgClass;
          if(imgval > fillmeval){
              imgClass = "stretchy";
          }else{
              imgClass = "stretchx";
          }
          $(this).children('img').addClass(imgClass);
       });
    });
    

    HTML:

    <div class="fillme">
       <img src="../images/myimg.jpg" />
    </div>
    

    CSS:

    .fillme{
      overflow:hidden;
    }
    .fillme img.stretchx{
      height:auto;
      width:100%;
    }
    .fillme img.stretchy{
      height:100%;
      width:auto;
    }
    
  • 59

    这对我有用

    div img {
        width: 100%;
        min-height: 500px;
        width: 100vw;
        height: 100vh;
        object-fit: cover;
    }
    
  • 1

    您可以在父div上使用 object-fit: cover; .

    https://css-tricks.com/almanac/properties/o/object-fit/

  • 9

    要使此图像拉伸到 maximum size possible without overflowing 它或倾斜图像 .

    应用...

    img {
      object-fit: cover;
      height: -webkit-fill-available;
    }
    

    图像的样式 .

  • 2

    如果你使用IMG标签,这很容易 .

    我做的:

    <style>
            #pic{
                height: 400px;
                width: 400px;
            }
            #pic img{
                height: 225px;               
                position: relative;
                margin: 0 auto;
            }
    </style>
    
    <div id="pic"><img src="images/menu.png"></div>
    
    $(document).ready(function(){
                $('#pic img').attr({ 'style':'height:25%; display:none; left:100px; top:100px;' })
    )}
    

    但我没有找到如何使用#pic {background:url(img / menu.png)} Enyone?谢谢

  • 4

    如果要在保持图像宽高比的同时设置最大宽度或高度(使其不会非常大),可以执行以下操作:

    img{
       object-fit: contain;
       max-height: 70px;
    }
    
  • 3

    HTML:

    <style>
    #foo, #bar{
        width: 50px; /* use any width or height */
        height: 50px;
        background-position: center center;
        background-repeat: no-repeat;
        background-size: cover;
    }
    </style>
    
    <div id="foo" style="background-image: url('path/to/image1.png');">
    <div id="bar" style="background-image: url('path/to/image2.png');">
    

    JSFiddle

    ...如果你想设置或更改图像(以#foo为例):

    jQuery的:

    $("#foo").css("background-image", "url('path/to/image.png')");
    

    JavaScript的:

    document.getElementById("foo").style.backgroundImage = "url('path/to/image.png')";
    
  • 3

    这里发现的许多解决方案都有一些限制:一些不在IE(对象适合)或旧版浏览器中工作,其他解决方案不能扩展图像(只缩小它),许多解决方案不支持窗口大小调整,许多是不通用,要么期望修复分辨率或布局(纵向或横向)

    如果使用javascript和jquery不是问题,我有基于@Tatu Ulmanen代码的解决方案 . 我解决了一些问题,并添加了一些代码情况下,图像是以动态方式加载的,并且在开始时不可用 . 基本上这个想法是有两个不同的css规则并在需要时应用它们:一个当限制是高度时,所以我们需要在两侧显示黑条,以及当限制是宽度时的其他css规则,所以我们需要在顶部/底部显示黑条 .

    function applyResizeCSS(){
        var $i = $('img#imageToResize');
        var $c = $i.parent();
        var i_ar = Oriwidth / Oriheight, c_ar = $c.width() / $c.height();  
        if(i_ar > c_ar){
            $i.css( "width","100%");
            $i.css( "height","auto");          
        }else{
            $i.css( "height","100%");
            $i.css( "width","auto");
        }
    }   
    var Oriwidth,Oriheight;
    $(function() {
        $(window).resize(function() {
            applyResizeCSS();
        });
    
        $("#slide").load(function(){
            Oriwidth  = this.width,
            Oriheight = this.height; 
            applyResizeCSS();
        }); 
    
        $(window).resize();
    });
    

    对于HTML元素,例如:

    <img src="images/loading.gif" name="imageToResize" id="imageToResize"/>
    

相关问题