Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

css - Force bootstrap responsive image to be square

Images are created in a loop with:

<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>

The images are from diffrent sizes some are higher then the width, and some are wider then the height. how can i force all images to have the same with as the height while being responsive. It is ok for them to have widh:100%, but i can not use height:auto, the ratio will stay then. What should i do to make my images squared while they are responsive and i dont know the %.

Example

Example, the green shirt is not as high as his width

I want to do this without jquery so CSS only!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this :

  1. wrap the image in a container with padding-bottom:100%; overflow:hidden; position:relative
  2. position the image absolutely inside that container.

FIDDLE

Explanation :

Padding top/bottom (like margin top/bottom) is calculated according to the width of parent element.As the .image div has the same width as its parent, setting padding-bottom:100%; give it the same height as its width so it is square (its content needs to be absolutely positioned or floated so it doesn't change the parent's size).

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>

CSS:

.image{
    position:relative;
    overflow:hidden;
    padding-bottom:100%;
}
.image img{
    position:absolute;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...