如何缩放一行图像以适合容器宽度?

时间:2014-12-09 12:07:39

标签: html css

我想显示一个可自动缩放以适合可用宽度的图像网格。每行的图像数量是任意的,并且可用宽度可以随着用户重新调整窗口大小而变化。原始图像也可以具有不同的宽度,但是每个都需要以相同的宽度显示。我更愿意避免使用表格,并且需要仅限CSS 解决方案。我设想的html类似于:

<div class='img-grid'>  <!-- one per page, typically fixed 70% of page width -->
  <!-- can be an arbitrary number of rows per grid -->
  <div class='row'>  <!-- width would be 100% of img-grid width -->
    <!-- can be an arbitrary number of images per row -->
    <div class='img-wrapper'>  <!-- wrapper needs to force images to same width -->
      <img class='image' src="test1.jpg"/>
    </div>
  </div>
</div>

看起来很简单,但我对4个类中每个类使用的css混淆强制图像宽度相同,缩放该宽度以使(任意数量)图像适合行而不包装并确保随着浏览器窗口宽度的变化,所有内容都会重新缩放。

由于 佰

3 个答案:

答案 0 :(得分:7)

您可以使用CSS表格布局,请参阅下面的演示。

JSFIDDLE DEMO

.row {
  display: table;
  border-collapse: collapse;
  width: 100%;
}
.item {
  display: table-cell;
  vertical-align: top;
}
.item img {
  display: block;
  width: 100%;
  height: auto;
}
<div class="row">
  <div class="item">
    <img src="//dummyimage.com/100x100/aaa" />
  </div>
  <div class="item">
    <img src="//dummyimage.com/200x200/bbb" />
  </div>
  <div class="item">
    <img src="//dummyimage.com/300x300/ccc" />
  </div>
</div>

答案 1 :(得分:2)

Flexbox在你的场景中非常有用:

display:flex添加到该行: 并flex: 1到行项目:

&#13;
&#13;
.img-grid { width: 70%; }
.row { width: 100%; display: flex; }
img { width: 100%;  }
.img-wrapper
{
    flex: 1;
}
&#13;
<div class='img-grid'>  <!-- one per page, typically fixed 70% of page width -->
  <!-- can be an arbitrary number of rows per grid -->
  <div class='row'>  <!-- width would be 100% of img-grid width -->
    <!-- can be an arbitrary number of images per row -->
        <div class='img-wrapper'>
  <img class='image' src="http://placeimg.com/440/680/any"/>
</div>
<div class='img-wrapper'>
  <img class='image' src="http://placeimg.com/640/380/any"/>
</div>
<div class='img-wrapper'>
  <img class='image' src="http://placeimg.com/540/480/any"/>
</div>
<div class='img-wrapper'>
  <img class='image' src="http://placeimg.com/640/280/any"/>
  </div>
<div class='img-wrapper'>
  <img class='image' src="http://placeimg.com/740/480/any"/>
</div>  
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

演示 - http://jsfiddle.net/u471prst/

&#13;
&#13;
* {
  box-sizing: border-box;
}
.img-grid {
  width: 70%;
  border: 2px solid red;
}
.row {
  width: 100%;
  border: 2px solid blue;
}
.img-wrapper {
  width: 100%;
}
.img-wrapper img {
  width: 100%;
  height: auto;
}
&#13;
<div class='img-grid'>
  <!-- one per page, typically fixed 70% of page width -->
  <!-- can be an arbitrary number of rows per grid -->
  <div class='row'>
    <!-- width would be 100% of img-grid width -->
    <!-- can be an arbitrary number of images per row -->
    <div class='img-wrapper'>
      <!-- wrapper needs to force images to same width -->
      <img class='image' src="http://placeimg.com/640/480/any" />
    </div>
  </div>
</div>
&#13;
&#13;
&#13;