使图像适合容器

时间:2016-07-12 07:47:11

标签: html css image absolute relative

我试图使用自举网格系统,每行有4列包含图像,但图像大小很大,它越过它的容器,所以我设置图像位置:绝对和div位置:相对但它仍然没有工作。有没有办法让图像适合容器大小的div容器?

HTML:

<div class="container">
        <div class="row">
            <div class="col-md-3 sec5row">
                <img class="filter" src="resources/images/f1.jpg" alt="f1">
            </div>
            <div class="col-md-3 sec5row">
                <img class="filter" src="resources/images/f2.jpg" alt="f1">
            </div>
            <div class="col-md-3 sec5row">
                <img class="filter" src="resources/images/f3.jpg" alt="f1">
            </div>
            <div class="col-md-3 sec5row">
                <img class="filter" src="resources/images/f4.jpg" alt="f1">
            </div>
     </div>
 <div>

CSS:

   .sec5row {
      border :  1px solid red;
      position: relative;
    }
     .filter {
      position: absolute;
    }

4 个答案:

答案 0 :(得分:3)

您可以使用以下代码将图像放入响应式div中

 .filter {
     width:100%;/*To occupy image full width of the container and also fit inside the container*/
     max-width:100%/*To fit inside the container alone with natural size of the image ,Use either of these width or max-width based on your need*/
    height:auto;
    }

答案 1 :(得分:3)

我认为bootstrap类“.img-responsive”解决了你的问题。所以尝试这样的事情:

<div class="container">
        <div class="row">
            <div class="col-md-3">
                <img class="img-responsive" src="resources/images/f1.jpg" alt="f1">
            </div>
            <div class="col-md-3">
                <img class="img-responsive" src="resources/images/f2.jpg" alt="f1">
            </div>
            <div class="col-md-3">
                <img class="img-responsive" src="resources/images/f3.jpg" alt="f1">
            </div>
            <div class="col-md-3">
                <img class="img-responsive" src="resources/images/f4.jpg" alt="f1">
            </div>
     </div>
 <div>

它将图像的样式设置为“max-width:100%;”和“身高:汽车;”这应该是你需要的。不需要任何额外的CSS。

答案 2 :(得分:2)

将css添加到您的代码中

#img {
    width: 100px;//change px size
    height: 100px;//change px size
    padding-left: 3px;
    padding-top: 5px;
}

答案 3 :(得分:0)

  

只需添加class =&#34; img-responsive&#34;你的img标签...它工作正常