2015-10-26 17 views
0

我正在拉取所有不同尺寸的图像,但希望它们是由基于百分比宽度的内嵌块列表项构成的网格内的正方形。我建立的页面是:http://ohmydrifter.com/category/inspiration/,我的HTML是:可能使用overflow:hidden将img裁剪为正方形,但将比率保留在基于百分比的宽度容器中?

<ul id="inspiration-grid"> 

    <li class="mix"> 

      <div class="grid-thumbnail">  
       <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_post_thumbnail(); ?></a> 
      </div><!-- end grid-thumbnail -->  

      <h4><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h4> 

    </li> <!-- .mix --> 

</ul> <!-- end #inspiration-grid --> 

我的CSS是:

.grid-thumbnail { 
overflow: hidden; 
width: 184px; 
height: 184px; 
} 

它的工作原理,但我想要做的是有.grid缩略图的div是百分比宽度。在将图像裁剪为正方形的同时可以做到这一点吗?

+0

检查也'背景大小:cover' https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Background_and_Borders/Scaling_background_images – LGSon

回答

0

由于paddingmargin基于元素的宽度,所以可以使用一个小诀窍。

我们将width设置为我们想要的任何比例。然后我们将height设置为0。最后,我们使用padding-bottom来设置我们的容器的高度。因为填充是基于元素的宽度,所以我们使它与我们用于width的完全相同。

我的示例使用20%作为百分比大小。

.grid-thumbnail { 
    overflow: hidden; 
    width: 20%; 
    height: 0; 
    padding-bottom: 20%; 
} 

活生生的例子在这里:http://codepen.io/marceloa/pen/ojqayO

+0

在你具体的布局,你可以使用'100%'作为'width'和'padding-bottom'。 – Marcelo