简体   繁体   中英

HTML CSS Fit image in fixed size

I know this topic has been featured a couple times but none of the answers given to those questions fixed my problem. That's why I'm asking it here. I have a site where I have a standard Bootstrap card with an Image above it, But It looks like this在此处输入图片说明

How can I make the images so they automatically fit in the middle and don't look like they're stretched out?

This is my HTML code (There is no CSS attached, Its standard bootstrap)

<div class="row mt-4">
            <div class="col-md-4">
                <div class="card mb-4">
                    <div class="card-image">
                        <img class="card-img-top" src="images/example.png">
                    </div>

                    <div class="card-header">
                        <h6 class="m-0">Some text</h6>
                    </div>
                    <div class="card-body" style="height: 130px">

                        <p class="m-0">Some text</p>

                    </div>
                    <div class="card-footer">

                        Footer
                    </div>
                </div>
            </div>
</div>

The best thing to do is to use the image as a background in conjunction with background cover. This will allow the photo to grow and resize without looking wonky.

 .card-header { height:200px; background-image:url('http://www.fillmurray.com/g/500/200'); background-size:cover; background-position:center center; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/> <div class="row mt-4"> <div class="col-md-4"> <div class="card mb-4"> <div class="card-image"> <img class="card-img-top sr-only" src="images/example.png"> </div> <div class="card-header"> <h6 class="m-0">Some text</h6> </div> <div class="card-body" style="height: 130px"> <p class="m-0">Some text</p> </div> <div class="card-footer"> Footer </div> </div> </div> </div>

add this to your 'img' styling:

img { height: 200px;width:100%;object-fit: cover; }

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