2015-06-02 35 views
16

我有一个图像列表,我希望图像缩放到他们的容器中具有相同的大小。 这样的:如何缩放图像以适合容器?

a b

我创建了一个jsfiddle

<div class="container"> 
    <div class="row"> 
     <div class="col-xs-3"> 
      <a href="#" class="thumbnail"> 
       <img src="http://exmoorpet.com/wp-content/uploads/2012/08/cat.png"> 
      </a> 
     </div> 
     <div class="col-xs-3"> 
      <a href="#" class="thumbnail"> 
       <img src="http://www.nose2tail.co.uk/cat-matlock-derbyshire.jpg"> 
      </a> 
     </div> 
     <div class="col-xs-3"> 
      <a href="#" class="thumbnail"> 
       <img src="http://www.us.onsior.com/images/3_1/cat-3_1-01.png"> 
      </a> 
     </div> 
     <div class="col-xs-3"> 
      <a href="#" class="thumbnail"> 
       <img src="https://www.petfinder.com/wp-content/uploads/2012/11/155293403-cat-adoption-checklist-632x475-e1354290788940.jpg" > 
      </a> 
     </div> 
    </div> 
</div> 

我怎么能这样做? 在我的例子中,我定义了height:100px;这导致没有响应,如果我调整浏览器的大小,div的高度保持不变。如果可能,我希望这个图像列表响应。

+0

这可以帮助你.. http://jsfiddle.net/68b3g7pw/2/ –

+0

参见:http://stackoverflow.com/a/30252800/59087 –

回答

22

heightwidth更改为max-heightmax-width。图像不会比它的父母大。

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

Updated Fiddle

+0

如何制作img对齐中心(水平和垂直)?在我的例子中,我定义了'height:100px;',这导致不响应,如果我调整浏览器的大小,div的高度保持不变。 – Sato

+2

您可以使用'display:table-cell;'with'vertical-align:middle;' http://jsfiddle.net/7gk6squL/ –

+0

这是一个答案(我看了十几个类似的问题),这将实际上做我正在寻找!无论周围div的大小如何,图像都会保持其纵横比,缩小/扩大图像以适应100%最相关的一面。 – DerProgrammer

0

这应该帮助,至少你的榜样。可能有些情况下这不起作用。在这种情况下,你必须找到一个JS解决方案。

.thumbnail img { 
    height: 100%; 
    width: auto; 
} 
5
.thumbnail { 
    height: 100px; 
    display: table; 
} 

.thumbnail img { 
    height: 100%; 
    width: 100%; 
    display: table-cell; 
    vertical-align: middle; 
} 
0
.thumbnail img { 
height: 100%; 
    width: 100%; 
} 

使用此。

0
.thumbnail { 
     height: 100%; 
    } 

    .thumbnail img { 
     max-height: 100%; 
     max-width: 100%; 
     border: 1px solid red; 
    } 
0

(我会虽然这是一个老问题,添加一个答案。我有同样的问题,直到我加入了类thumbnail的图像链接,看起来有点更深。无添加CSS是必要的。)

也许有所改变。在Bootstrap 3.3.7中。有这个(非minified的CSS,行5019):

.thumbnail > img, 
.thumbnail a > img { 
    margin-left: auto; 
    margin-right: auto; 
} 

这(非精缩CSS,行1124):

.img-responsive, 
.thumbnail > img, 
.thumbnail a > img, 
.carousel-inner > .item > img, 
.carousel-inner > .item > a > img { 
    display: block; 
    max-width: 100%; 
    height: auto; 
} 

所以一切都应该工作的权利开箱,如果你已将类thumbnail添加到图像链接。 (您需要删除这两个和东西会打破。),并将其带或不带附加CSS的工作原理:

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

添加的CSS覆盖白手起家的风格,至少对我来说,因为添加的样式后,包括Bootstraps拥有自己的风格。 (但它是多余的。)

1

在2017年,你可以使用flex。此外,您将在缩略图容器得到中心的图片:updated fiddle

.thumbnail { 
    height: 300px; 
    display: flex; 
    flex-direction: column; 
    justify-content: center; 
    align-items: center; 
    border: solid 1px blue; 
} 

.thumbnail img { 
    max-width: 100%; 
    max-height: 100%; 
    display: block; 
    margin: 0 auto; 
    border: solid 1px red; 
}