显示像background-size:contains的img标签

时间:2016-06-30 12:04:03

标签: html css

是否可以使用background-size: contain标记获得类似img的效果?

我想在固定宽度/高度div容器内显示产品图片,这些容器有各种尺寸(方形,纵向,横向)。图片应该

  • 始终显示整个图像,不应裁剪任何内容
  • 水平和垂直居中对齐

这是background-size: contain的作用。不幸的是,我必须使用img标签(由于各种原因,从我使用的框架到SEO的东西)。

在此plnkr中,您可以看到问题及其外观(使用background-sizehttp://plnkr.co/edit/k9Nv4ELoZgYCaQfVuSDQ?p=preview

  1. 看起来不错
  2. 应垂直居中
  3. 被裁剪,但应显示其高度的100%
  4. CSS:

    .product {
      background-color: green;
      border: 1px solid blue;
      width: 200px;
      height: 200px;
      overflow: hidden;
      margin-bottom: 20px;
    }
    
    .product img {
      width: 100%;
    }
    
      

    注意:不知怎的,我无法插入HTML标记,它显示的图像不是   源代码。请看一下plnkr。

    编辑:

      
        
    • 这应该只适用于CSS,没有JS。
    •   
    • 支持所有现代浏览器,包括IE 10
    •   

2 个答案:

答案 0 :(得分:5)

您可以将position: relative设置为.product,将position: absolute设置为.product img的其他格式设置,即可完成此操作。请检查下面的小提琴。



.product-css {
  background-color: red;
  border: 1px solid blue;
  width: 200px;
  height: 200px;
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  margin-bottom: 20px;
}
.product {
  background-color: green;
  border: 1px solid blue;
  width: 200px;
  height: 200px;
  overflow: hidden;
  margin-bottom: 20px;
  position: relative;
}
.product img {
  max-width: 100%;
  max-height: 100%;
  position: absolute;
  top: -100%;
  bottom: -100%;
  left: -100%;
  right: -100%;
  margin: auto;
}

<h2>With img tag</h2> 1.
<div class="product">
  <img src="http://keentype.com/post-images/wineBottles/vine-bottles-post.jpg">
</div>

2.
<div class="product">
  <img src="https://0.s3.envato.com/files/149175458/wine_bottle_mockup_05.jpg">
</div>

3.
<div class="product">
  <img src="http://www.designer-daily.com/wp-content/uploads/2009/02/boxhead-wine.jpg">
</div>

<hr>

<h2>Desired behaviour (with background-image)</h2>

<div class="product-css" style="background-image: url(http://keentype.com/post-images/wineBottles/vine-bottles-post.jpg)">
</div>

<div class="product-css" style="background-image: url(https://0.s3.envato.com/files/149175458/wine_bottle_mockup_05.jpg)">
</div>

<div class="product-css" style="background-image: url(http://www.designer-daily.com/wp-content/uploads/2009/02/boxhead-wine.jpg)">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

尝试添加此css:

.product img {
  max-width: 200px;
  max-height:200px;
  width:auto;
  height:auto;
  margin: 0 auto;
  display: block;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
相关问题