首页 文章

Bootstrap响应图像适合父高,拉伸全宽

提问于
浏览
1

我有一个具有一定高度的行(例如600px),并且想要将img(大小为1920x1080)放入该行中,相应地100%延伸到行宽但不超过高度 .

换句话说,应该只显示600px的图像高度(其余部分可以被剪切,隐藏等),并且它应该保持对行宽度的响应 . 为了说明,只有红色边框内的部分应显示:

enter image description here

我遇到的问题是“img-fluid”总是使图像适合容器的较小高度,从而缩小宽度以保持纵横比 . 如果没有img-fluid,或者为图像添加固定高度,则会丢失纵横比并将图像“挤压”到行容器中 . 我的代码:

.img-400 {
  height: 400px !important;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<div class="container">
  <div class="row img-400">
    <div class="col-12">
      <img src="https://image.ibb.co/iG8OSb/dogs.jpg" class="img-fluid" />
    </div>
  </div>
</div>

注意我尝试了这个:Constraining image height with bootstrap responsive image?但是没有用,它不断地将img从容器中扩展出来 .

3 回答

  • 0

    如果不操作.img-fluid,上述解决方案有效:

    .img-400 {
      height: 400px;
      overflow: hidden;
    }
    
  • 1

    要使图像适合特定高度,可以通过NPM使用开源库bootstrap-spacer

    npm install uniformimages
    

    或者您可以访问github页面:

    https://github.com/chigozieorunta/uniformimages
    

    下面是一个如何使用“unim”类(你需要jQuery)的例子:

    <!DOCTYPE html>
    <html>
    <head>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
          <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
          <link href="uniformimages.css" rel="stylesheet" type="text/css"/>
          <script src="uniformimages.js" type="text/javascript"></script>
    </head>
    
    <body>
        <section>
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-12">
                        <a href="product1.html">
                            <img src="image1.jpg" class="unim" height="100"/>
                        </a>
                    </div>
                </div>
            </div>
        </section>
    </body>
    
  • -1

    嗨试试这个,

    .img-400 img{ width: 100% ; }
    

    希望这可以帮助 :)

相关问题