简体   繁体   中英

Responsive card image with fixed height in bootstrap 4

I have an image with a resolution of 760x270, for example, but this ratio makes it look too thin and I want it to look more like a square. However, if I put a more square-ish image with a resolution 760x500 for example, I want it to still fit and not distort. How can I do this?

<div class="col-xs-6 col-md-4">
                        <div class="card">
                            <img class="card-img-top img-fluid" src="img/1.jpg" alt="Card image cap">
                            <h4 class="card-title">Title</h4>
                            <div class="card-body">
                                <p class="card-text">Some quick example text to build on </p>
                                10 mins ago <div class="float-right"><i class="fa fa-comment-o" aria-hidden="true"></i> 0</div>
                            </div>
                        </div>
                    </div><!--/span-->

You can force a 1:1 ratio with a wrapper using the "padding trick" and then absolutely position the image in the wrapper so that it is centered and takes up 100% of the height of the wrapper (click "full page" after running the snippet to adjust the window size):

 .wrapper { position: relative; overflow: hidden; } .wrapper:after { content: ''; display: block; padding-top: 100%; } .wrapper img { width: auto; height: 100%; max-width: none; position: absolute; left: 50%; top: 0; transform: translateX(-50%); } 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <div class="row"> <div class="col-xs-6 col-md-4"> <div class="card"> <div class="wrapper"> <img class="card-img-top img-fluid" src="//placehold.it/760x270" alt="Card image cap"> </div> <h4 class="card-title">Title</h4> <div class="card-body"> <p class="card-text">Some quick example text to build on </p> 10 mins ago <div class="float-right"><i class="fa fa-comment-o" aria-hidden="true"></i> 0</div> </div> </div> </div> <div class="col-xs-6 col-md-4"> <div class="card"> <div class="wrapper"> <img class="card-img-top img-fluid" src="//placehold.it/760x500" alt="Card image cap"> </div> <h4 class="card-title">Title</h4> <div class="card-body"> <p class="card-text">Some quick example text to build on </p> 10 mins ago <div class="float-right"><i class="fa fa-comment-o" aria-hidden="true"></i> 0</div> </div> </div> </div> </div> </div> 

Not that this is for a 1:1 ratio. To adjust this ratio compute it as a percent. For 4:3, this would be 3 / 4 = 0.75 . 0.75 as a percent would be 75% . You would use this as the padding-top value of .wrapper:after .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM