强制自举响应图像为方形

Sve*_*art 23 css responsive-design twitter-bootstrap

图像是在循环中创建的:

<div id="row">
    <div class="col-sm-6">
        <div id="row">
        <?php
        foreach ($products as $product)
        {
        ?>
            <div class="col-sm-6">
                <a href="/admin/product/"   class="thumbnail">
                <div class="caption">
                    title<br>
                    10  x viewed
                </div>
                <img src="/assets/img/product/<?php echo $product['img'] ?>" class="img img-responsive full-width" />
                </a>
            </div>
        <?php
        }
        ?>
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

图像来自不同的尺寸,有些高于宽度,有些比高度宽.如何在响应时强制所有图像与高度相同.他们可以拥有widh:100%,但我不能使用身高:自动,比率将保持不变.我应该怎么做才能使我的图像在响应时平方,我不知道%.

例

例如,绿色衬衫不如他的宽度高

我想这样做没有jquery所以只有CSS!

web*_*iki 57

你可以这样做 :

  1. 将图像包装在容器中 padding-bottom:100%; overflow:hidden; position:relative
  2. 将图像绝对放在该容器内.

小提琴

说明:

填充顶部/底部(如边缘顶部/底部)根据父元素的宽度计算.由于.imagediv具有与其父元素相同的宽度,因此设置padding-bottom:100%;给它与其宽度相同的高度,因此它是正方形(其内容需要绝对定位或浮动,所以它不会改变父母的大小).

HTML:

<div class="col-sm-6"> 
    <a href="#" class="thumbnail">
        <div class="caption">
            title<br/>3 x bekeken
        </div>
        <div class="image">
            <img src="" class="img img-responsive full-width" />
        </div>
    </a>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

.image{
    position:relative;
    overflow:hidden;
    padding-bottom:100%;
}
.image img{
    position:absolute;
}
Run Code Online (Sandbox Code Playgroud)


obo*_*hto 22

这是各种尺寸图像的最佳解决方案 http://jsfiddle.net/oboshto/p9L2q/53/

HTML相同:

<div class="col-sm-6"> 
    <a href="#" class="thumbnail">
        <div class="caption">
            title<br/>3 x bekeken
        </div>
        <div class="image">
            <img src="" class="img img-responsive full-width" />
        </div>
    </a>
</div>
Run Code Online (Sandbox Code Playgroud)

新CSS:

.image{
    position:relative;
    overflow:hidden;
    padding-bottom:100%;
}
.image img{
      position: absolute;
      max-width: 100%;
      max-height: 100%;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
}
Run Code Online (Sandbox Code Playgroud)

  • 这个确实有效。上面的 web-tiki 示例对于肖像图像效果不佳(它会裁剪它们而不是将它们放入正方形中)。 (2认同)