首页 文章

是否有相当于背景大小:覆盖和包含图像元素?

提问于
浏览
156

我有一个有很多页面和不同背景图片的网站,我从CSS中显示它们:

body.page-8 {
    background: url("../img/pic.jpg") no-repeat scroll center top #000;
    background-size: cover;
}

但是,我想使用 <img> 元素在一个页面上显示不同的(全屏)图片,并且我希望它们具有与上述 background-image: cover; 属性相同的属性(图像无法从CSS显示,它们必须从HTML文档中显示) .

通常我使用:

div.mydiv img {
    width: 100%;
}

要么:

div.mydiv img {
    width: auto;
}

使图片充分和响应 . 然而,当屏幕变得太窄时,图片会缩小太多( width: 100% ),并在底部屏幕中显示正文的背景颜色 . 另一种方法 width: auto; 仅使图像成为完整大小而不响应屏幕大小 .

有没有办法以 background-size: cover 的方式显示图像?

14 回答

  • 24

    尝试使用 display:block 同时设置 min-heightmin-width

    img {
        display:block;
        min-height:100%;
        min-width:100%;
    }
    

    fiddle

    如果您的图像包含元素是 position:relativeposition:absolute ,则图像将覆盖容器 . 但是,它不会居中 .

    如果您知道图像是水平溢出(设置 margin-left:-50% )还是垂直放置(设置 margin-top:-50% ),则可以轻松居中 . 有可能使用CSS媒体查询(和一些数学)来解决这个问题 .

  • 2

    我需要模拟 background-size: contain ,但由于缺乏支持而无法使用 object-fit . 我的图片有定义尺寸的容器,最终为我工作:

    .image-container {
      height: 200px;
      width: 200px;
      overflow: hidden;
      background-color: rebeccapurple;
      border: 1px solid yellow;
      position: relative;
    }
    
    .image {
      max-height: 100%;
      max-width: 100%;
      margin: auto;
      position: absolute;
      transform: translate(-50%, -50%);
      top: 50%;
      left: 50%;
    }
    
    <!-- wide -->
    <div class="image-container">
      <img class="image" src="http://placehold.it/300x100">
    </div>
    
    <!-- tall -->
    <div class="image-container">
      <img class="image" src="http://placehold.it/100x300">
    </div>
    
  • 8

    使用CSS,您可以模拟 object-fit: [cover|contain]; . 这是使用 transform[max|min]-[width|height] . It's not perfect. 在一种情况下不起作用:如果图像比容器更宽更短 .

    .img-ctr{
      background: red;/*visible only in contain mode*/
      border: 1px solid black;
      height: 300px;
      width: 600px;
      overflow: hidden;
      position: relative;
      display: block;
    }
    .img{
      display: block;
    
      /*contain:*/
      /*max-height: 100%;
      max-width: 100%;*/
      /*--*/
    
      /*cover (not work for images wider and shorter than the container):*/
      min-height: 100%;
      width: 100%;
      /*--*/
    
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    <p>Large square:
    <span class="img-ctr"><img class="img" src="http://placehold.it/1000x1000"></span>
    </p>
    <p>Small square:
    <span class="img-ctr"><img class="img" src="http://placehold.it/100x100"></span>
    </p>
    <p>Large landscape:
    <span class="img-ctr"><img class="img" src="http://placehold.it/2000x1000"></span>
    </p>
    <p>Small landscape:
    <span class="img-ctr"><img class="img" src="http://placehold.it/200x100"></span>
    </p>
    <p>Large portrait:
    <span class="img-ctr"><img class="img" src="http://placehold.it/1000x2000"></span>
    </p>
    <p>Small portrait:
    <span class="img-ctr"><img class="img" src="http://placehold.it/100x200"></span>
    </p>
    <p>Ultra thin portrait:
    <span class="img-ctr"><img class="img" src="http://placehold.it/200x1000"></span>
    </p>
    <p>Ultra wide landscape (images wider and shorter than the container):
    <span class="img-ctr"><img class="img" src="http://placehold.it/1000x200"></span>
    </p>
    
  • 2

    解决方案#1 - 对象适配属性(缺乏IE支持)

    只需在img上设置 object-fit: cover; 即可 .

    body {
      margin: 0;
    }
    img {
      display: block;
      width: 100vw;
      height: 100vh;
      object-fit: cover;
    }
    
    <img src="http://lorempixel.com/1500/1000" />
    

    MDN - 关于 object-fit: cover

    替换内容的大小可以在填充元素的整个内容框时保持其宽高比 . 如果对象的宽高比与其框的宽高比不匹配,则剪裁对象以使其适合 .

    另外,请参阅this Codepen demo,它将应用于图像的 object-fit: cover 与应用于背景图像的 background-size: cover 进行比较


    解决方案#2 - 用css替换带有背景图像的img

    body {
      margin: 0;
    }
    img {
      position: fixed;
      width: 0;
      height: 0;
      padding: 50vh 50vw;
      background: url(http://lorempixel.com/1500/1000/city/Dummy-Text) no-repeat;
      background-size: cover;
    }
    
    <img src="http://placehold.it/1500x1000" />
    
  • 0

    我知道这是旧的,但我上面看到的许多解决方案都存在图像/视频对于容器来说太大的问题,因此实际上不像背景大小的覆盖 . 但是,我决定制作“实用程序类”,以便它可以用于图像和视频 . 您只需为容器提供类.media-cover-wrapper,将媒体项本身设为类.media-cover

    然后你有以下jQuery:

    function adjustDimensions(item, minW, minH, maxW, maxH) {
      item.css({
      minWidth: minW,
      minHeight: minH,
      maxWidth: maxW,
      maxHeight: maxH
      });
    } // end function adjustDimensions
    
    function mediaCoverBounds() {
      var mediaCover = $('.media-cover');
    
      mediaCover.each(function() {
       adjustDimensions($(this), '', '', '', '');
       var mediaWrapper = $(this).parent();
       var mediaWrapperWidth = mediaWrapper.width();
       var mediaWrapperHeight = mediaWrapper.height();
       var mediaCoverWidth = $(this).width();
       var mediaCoverHeight = $(this).height();
       var maxCoverWidth;
       var maxCoverHeight;
    
       if (mediaCoverWidth > mediaWrapperWidth && mediaCoverHeight > mediaWrapperHeight) {
    
         if (mediaWrapperHeight/mediaWrapperWidth > mediaCoverHeight/mediaCoverWidth) {
           maxCoverWidth = '';
           maxCoverHeight = '100%';
         } else {
           maxCoverWidth = '100%';
           maxCoverHeight = '';
         } // end if
    
         adjustDimensions($(this), '', '', maxCoverWidth, maxCoverHeight);
       } else {
         adjustDimensions($(this), '100%', '100%', '', '');
       } // end if
     }); // end mediaCover.each
    } // end function mediaCoverBounds
    

    调用它时一定要注意页面大小调整:

    mediaCoverBounds();
    
    $(window).on('resize', function(){
      mediaCoverBounds();
    });
    

    然后是以下CSS:

    .media-cover-wrapper {
      position: relative;
      overflow: hidden;
    }
    
    .media-cover-wrapper .media-cover {
      position: absolute;
      z-index: -1;
      top: 50%;
      left: 50%;
      -ms-transform: translate(-50%, -50%);
      -moz-transform: translate(-50%, -50%);
      -webkit-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
    }
    

    是的,它可能需要jQuery,但它响应很好,行为完全像背景大小:封面,你可以在图像和/或视频上使用它来获得额外的SEO值 .

  • 2

    对于IE,你还需要包括第二行 - 宽度:100%;

    .mydiv img {
        max-width: 100%;
        width: 100%;
    }
    
  • 2

    我们可以采取ZOOM方法 . 如果方位图像高度或宽度小于期望的高度或宽度,我们可以假设最大30%(或多达100%)可以是缩放效果 . 我们可以通过溢出隐藏其余不需要的区域:隐藏 .

    .image-container {
      width: 200px;
      height: 150px;
      overflow: hidden;
    }
    .stage-image-gallery a img {
      max-height: 130%;
      max-width: 130%;
      position: relative;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
    }
    

    这将调整具有不同宽度或高度的图像 .

  • -1

    我不允许“添加评论”所以这样做,但是Eru Penkman所做的事情是非常重要的,为了让它像背景一样,你需要做的就是改变

    .tall-img{
        margin-top:-50%;
        width:100%;
    }
    .wide-img{
        margin-left:-50%;
        height:100%;
    }
    

    .wide-img{
        margin-left:-42%;
        height:100%;
    }
    .tall-img{
        margin-top:-42%;
        width:100%;
    }
    
  • 0

    你可以做的是使用'style'属性将背景图像添加到元素,这样你仍然可以在HTML中调用图像,但你仍然可以使用background-size:cover css行为:

    HTML:

    <div class="image-div" style="background-image:url(yourimage.jpg)">
        </div>
    

    CSS:

    .image-div{
        background-size: cover;
        }
    

    这就是我将background-size:cover行为添加到我需要动态加载到HTML中的元素的方法 . 然后,您可以使用像background-position:center这样的令人敬畏的CSS类 . 繁荣

  • 0
    background:url('/image/url/') right top scroll; 
    background-size: auto 100%; 
    min-height:100%;
    

    遇到了同样精确的症状 . 上面为我工作 .

  • 0

    我发现了一个简单的解决方案来模拟封面和包含,它是纯CSS,适用于具有动态尺寸的容器,并且对图像比率没有任何限制 .

    请注意,如果您不需要在16之前支持IE或Edge,那么最好使用object-fit .

    background-size:封面

    .img-container {
      position: relative;
      overflow: hidden;
    }
    
    .background-image {
      position: absolute;
      min-width: 1000%;
      min-height: 1000%;
      left: 50%;
      top: 50%;
      transform: translateX(-50%) translateY(-50%) scale(0.1);
      z-index: -1;
    }
    
    <div class="img-container">
      <img class="background-image" src="https://picsum.photos/1024/768/?random">
      <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      </p>
    </div>
    

    如果图像自然尺寸大于显示的尺寸,则使用1000% . 例如,如果图像是500x500,但容器只有200x200 . 使用此解决方案,图像将调整为2000x2000(由于最小宽度/最小高度),然后缩小到200x200(由于 transform: scale(0.1) ) .

    x10因子可以用x100或x1000代替,但在20x20 div上渲染2000x2000图像通常并不理想 . :)

    background-size:包含

    遵循相同的原则,您也可以使用它来模拟 background-size: contain

    .img-container {
      position: relative;
      overflow: hidden;
      z-index: 0;
    }
    
    .background-image {
      position: absolute;
      max-width: 10%;
      max-height: 10%;
      left: 50%;
      top: 50%;
      transform: translateX(-50%) translateY(-50%) scale(10);
      z-index: -1;
    }
    
    <div style="background-color: black">
      <div class="img-container">
        <img class="background-image" src="https://picsum.photos/1024/768/?random">
        <p style="padding: 20px; color: white; text-shadow: 0 0 10px black">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
        </p>
      </div>
    </div>
    
  • 12

    实际上有一个非常简单的css solution甚至适用于IE8:

    .container {
      position: relative;
      overflow: hidden;
      /* Width and height can be anything. */
      width: 50vw;
      height: 50vh;
    }
    
    img {
      position: absolute;
      /* Position the image in the middle of its container. */
      top: -9999px;
      right: -9999px;
      bottom: -9999px;
      left: -9999px;
      margin: auto;
      /* The following values determine the exact image behaviour. */
      /* You can simulate background-size: cover/contain/etc.
         by changing between min/max/standard width/height values.
         These values simulate background-size: cover
      */
      min-width: 100%;
      min-height: 100%;
    }
    
    <div class="container">
        <img src="http://placehold.it/200x200" alt="" />
    </div>
    
  • 0

    假设你可以安排一个你希望填充的容器元素,这似乎有效,但感觉有点hackish . 本质上,我只是在更大的区域使用 min/max-width/height 然后将该区域缩放回原始尺寸 .

    .container {
      width: 800px;
      height: 300px;
      border: 1px solid black;
      overflow:hidden;
      position:relative;
    }
    .container.contain img {
      position: absolute;
      left:-10000%; right: -10000%; 
      top: -10000%; bottom: -10000%;
      margin: auto auto;
      max-width: 10%;
      max-height: 10%;
      -webkit-transform:scale(10);
      transform: scale(10);
    }
    .container.cover img {
      position: absolute;
      left:-10000%; right: -10000%; 
      top: -10000%; bottom: -10000%;
      margin: auto auto;
      min-width: 1000%;
      min-height: 1000%;
      -webkit-transform:scale(0.1);
      transform: scale(0.1);
    }
    
    <h1>contain</h1>
      <div class="container contain">
        <img 
           src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" 
           />
        <!-- 366x200 -->
      </div>
      <h1>cover</h1>
      <div class="container cover">
        <img 
           src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" 
           />
        <!-- 366x200 -->
      </div>
    
  • 268

    No ,你不能像 background-size:cover but.. 那样得到它

    这种方法非常接近:它使用JavaScript来确定图像是横向还是纵向,并相应地应用样式 .

    JS

    $('.myImages img').load(function(){
            var height = $(this).height();
            var width = $(this).width();
            console.log('widthandheight:',width,height);
            if(width>height){
                $(this).addClass('wide-img');
            }else{
                $(this).addClass('tall-img');
            }
        });
    

    CSS

    .tall-img{
        margin-top:-50%;
        width:100%;
    }
    .wide-img{
        margin-left:-50%;
        height:100%;
    }
    

    http://jsfiddle.net/b3PbT/

相关问题