stretched image in carousel bootstrap

2019-07-15 04:07发布

问题:

I am using Bootstrap 4. There I have a carousel with picture. The images keep showing stretched. Idk what's the problem.

.carousel {
  margin-bottom: 4rem;
  position: relative;
}

.carousel-caption {
  bottom: 3rem;
  z-index: 10;
}

.carousel-inner img {
  position: absolute;
  top: 0;
  left: 0;
  height: 32rem;
  object-fit: containt !important;
  display: block;
}

.carousel-item {
  height: 32rem;
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.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 id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active col-xs-12 col-sm-12">
      <img src="https://i.stack.imgur.com/cPtnU.jpg" class="d-block w-100" alt="...">
      <div class="carousel-caption d-none d-md-block">
        <h1>Lorem</h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, minima.</p>
      </div>
    </div>
    <div class="carousel-item col-xs-12 col-sm-12">
      <img src="https://i.stack.imgur.com/cPtnU.jpg" class="d-block w-100" alt="...">
      <div class="carousel-caption d-none d-md-block">
        <h1>Lorem</h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, minima</p>
      </div>
    </div>
    <div class="carousel-item col-xs-12 col-sm-12">
      <img src="https://i.stack.imgur.com/cPtnU.jpg" class="d-block w-100" alt="...">
      <div class="carousel-caption d-none d-md-block">
        <h1>Lorem</h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Provident, minima</p>
      </div>
    </div>
  </div>
</div>

It looks like this:

The original pic looks like this:

Can someone please help me to solve this problem?

回答1:

Instead of using object-fit: contain !important;, have you tried using object-fit: cover !important; to achieve your desired effect?

I am assuming you are wanting to place the background in a position where it will cover from left to right as well as top to bottom without morphing the image? For this I use background-size: cover; or object-fit: cover;.



回答2:

you can chnage the value of img height yo auto

.carousel-inner img {
  position: absolute;
  top: 0;
  left: 0;
  height: auto
  object-fit: containt !important;
  display: block;
}

or add the width auto and keep the height value :

.carousel-inner img {
  ....
  height: 32rem;
  ....
  width : auto; /* or 100% */
}