【问题标题】:Fill an image in a square container while keeping aspect ratio将图像填充到方形容器中,同时保持纵横比
【发布时间】:2014-06-09 22:33:04
【问题描述】:

我正在尝试在 CSS 中使用非正方形的随机大小的图像制作图像网格。 有没有人可以用图像填充固定大小的 div 内的所有空间?

看我的例子(蓝色是一个固定大小的div,里面的图片是红色的:

【问题讨论】:

  • if height > width => 以宽度为边.. 否则以高度为边。使用 javascript 或 jquery 来完成。
  • 亚当,如果你不解释你已经尝试过的东西,人们可能会给你带来困难。为我们发布一些代码

标签: javascript jquery html css


【解决方案1】:

可以使用css, background-size:cover;

<style>
    .img1 {
        background-image: url(microsoft-logo.png);
    }
    .img2 {
        background-image: url(google-icon.png);
    }
    .img3 {
        background-image: url(Azend_Loggo.png);
    }
    .img-cover {
        width: 50px;
        height: 50px;
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
    }
</style>

<div class="img-cover img1">

</div>
<div class="img-cover img2">

</div>
<div class="img-cover img3">

</div>

【讨论】:

    【解决方案2】:

    使用这个 CSS 规则:

    background-size: cover;
    background-position: center;
    

    DEMO

    【讨论】:

      【解决方案3】:

      我有一些代码可以做到这一点,并允许您设置所需的大小......

      <?PHP
      function imageResize($image,$maxwidth,$maxheight) {
          $imgData = getimagesize("img/profiles/".$image);    
          $width  = $imgData[0];
          $height = $imgData[1];
          // takes the larger size of the width and height and applies the
          // formula accordingly...this is so this script will work
          // dynamically with any size image
          // First we'll scale down the width since it's the larger of the tw values
          if ($width > $maxwidth) {
              $percentage = ($maxwidth / $width);
              $width = round($width * $percentage);
              $height = round($height * $percentage);
          }
          // Next we'll scale down the height since it's the larger of the tw values
          if ($height > $maxheight) {
              $percentage = ($maxheight / $height);
              $width = round($width * $percentage);
              $height = round($height * $percentage);
          }
          $topMargin = ($maxheight-$height)/2;
          $topMargin .= "px";
          //returns the new sizes in html image tag format...
          // this is so you can plug this function inside an image tag and just get the results
          return "width=\"$width\" height=\"$height\" style=\"margin-top:$topMargin px;\"";
      }
      ?>
      

      然后包括以下内容:

      <div id="profile-picture">
          <img src="img/profiles/<?PHP echo $profileImg; ?>" <?PHP echo imageResize($profileImg,238,232); ?> />
      </div>
      

      不确定这是否有帮助..但它对我有用。

      【讨论】:

      • 开始认为我的解决方案不会考虑动态 div 的问题 .. 但稍作调整 .. 它“可以”
      【解决方案4】:

      您可以在此解决方案中尝试使用以下 css 作为固定 div 的图像标签,您必须遵循一个条件,即您的图像尺寸应该大于您的 div,即如果您的 div 为 100px,则最小图像尺寸应为 100px或更多:

      div > img {
       width:100%;
       overflow:hidden;
      } 
      

      【讨论】:

        【解决方案5】:

        看到你已经用jQuery 标记了这个问题,我冒昧地建议你为此编写一个小型 jQuery 插件。这是JSFiddle demo。

        // Define plugin 'containImg'
        $.fn.containImg = function(){
            this.each(function(){
                // Set variables
                var $t = $(this),
                    $p = $t.parent('div'),
                    pw = $p.width(),
                    ph = $p.height(),
                    // Figure if width or height should be 100%
                    iw = ( pw / ph >= 1 ) ? 'auto' : '100%',
                    ih = ( iw == 'auto' ) ? '100%' : 'auto';
                // Set dimensions
                $t.css({
                    'width': iw,
                    'height': ih
                });
            });
        }
        
        // Call plugin
        $('img').containImg();
        

        基本逻辑是如果图像有一个水平拉伸的父 div,你需要设置height:100% 来填充高度,并设置width:auto 来保持纵横比。如果父 div 形状是垂直的,则必须反转它。

        如果有人对如何改进代码有意见,我愿意提供建议!

        【讨论】:

          【解决方案6】:

          你可以只使用 css,但 js 可以提供帮助,这里按照我的简单代码。

              <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
          
          <html>
          <head>
              <title></title>
              <style type="text/css">
                  div.image-box{display:block;position:relative;overflow:hidden;width:200px;border:1px solid #ccc;padding:0;height:200px;}
                  div.image-box img{width:100%;height:auto;margin:0; padding:0;margin-bottom:-4px;position:absolute;top:0;left:0;}
                  div.image-box.horizontal img{height:100%;width:auto;left:50%;}
                  div.image-box.vertical img{height:auto;width:100%;top:50%;}
              </style>
          </head>
          
          <body>
              <div class="image-box"><img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS08-IWtcbvcehgeszlD2nI6s-OAungNCsLNIc-f3QjIOkvOq8abg" alt=""></div>
              <div class="image-box"><img src="http://1.bp.blogspot.com/_e-y-Rrz58H4/TUS4qRlRUrI/AAAAAAAABQo/H322eTHRB2s/s1600/Man_Face.jpg" alt=""></div>
          
              <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
              <script type="text/javascript">
                  $(document).ready(function(){
                      $('.image-box').each(function(){
                          if($(this).find('img').height() > $(this).find('img').width()){
                              $(this).addClass('vertical');
                              $(this).find('img').css('margin-top','-'+$(this).find('img').height()/2+'px');
                          }else{
                              $(this).addClass('horizontal');
                              $(this).find('img').css('margin-left','-'+$(this).find('img').width()/2+'px');
                          }
                      });
                  });
          
              </script>
          </body>
          </html>
          

          希望有帮助

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-12-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-03-26
            相关资源
            最近更新 更多