【问题标题】:How to make image fit in container?如何使图像适合容器?
【发布时间】:2019-09-12 02:25:24
【问题描述】:

我正在尝试使用 Bootstrap 网格系统,每行有 4 列包含图像,但图像大小很大并且它超过了它的容器,所以我设置图像 position: absolutediv position: relative 但它还是不行。有什么方法可以使图像适合容器大小的 div 容器?

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

.filter {
  position: absolute;
}
<div class="container">
  <div class="row">
    <div class="col-md-3 sec5row">
      <img class="filter" src="https://placehold.it/40" alt="f1">
    </div>
    <div class="col-md-3 sec5row">
      <img class="filter" src="https://placehold.it/40" alt="f1">
    </div>
    <div class="col-md-3 sec5row">
      <img class="filter" src="https://placehold.it/40" alt="f1">
    </div>
    <div class="col-md-3 sec5row">
      <img class="filter" src="https://placehold.it/40" alt="f1">
    </div>
  </div>
  <div>

【问题讨论】:

  • 只用 img {width:100%}
  • img{ max-width: 100%;} 可能会起作用。或者甚至是 img{width:100%;} 如果您希望它始终保持 100%。
  • 或者甚至可以更好地将引导类 img-responsive 添加到图像(假设您根据创建列的方式使用引导程序)。

标签: html css image css-position


【解决方案1】:

您可以使用以下代码将图像放入响应式 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;
    }

【讨论】:

  • 你能告诉我为什么 height :auto 吗?对不起,我是新人。
  • @pexichdu 根据宽度保持图像的纵横比,否则由于我们将宽度设置为 100%,因此图像看起来会被拉伸
【解决方案2】:

我认为引导类“.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>

它将图像的样式设置为“最大宽度:100%;”和“高度:自动;”这应该正是您所需要的。应该不需要任何额外的 css。

【讨论】:

    【解决方案3】:

    将 css 添加到您的代码中

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

    【讨论】:

    • 为什么是#img ?? img标签没有ID
    • 制作一个简单的 id=" " 它不会影响任何事情。
    • 或使用类似“.filter”的类
    【解决方案4】:

    只需将 class="img-responsive" 添加到您的 img 标签...它工作正常

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-09
      • 1970-01-01
      • 2020-08-05
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 2013-04-08
      相关资源
      最近更新 更多