我试图找出一种使响应的图像行具有相同高度的方法,而不管每个图像的纵横比或容器的宽度如何。实际图像文件的高度相同,但宽度不同。问题在于,当容器变小时,在某些宽度处的舍入误差会导致图像的高度为一个像素或两个不同。这是一个小提琴http://jsfiddle.net/chris_tsongas/vj2rfath/,调整结果窗格的大小,您将看到某些宽度的图像不再具有相同的高度。
我正在从CMS设计内容的样式,因此对标记的控制最小,并且具有仅使用CSS而非js的权限。我尝试将图像高度设置为100%,但这只是使图像达到其原始大小的100%,而不是容器高度的100%。这是上面链接的小提琴的html和css:
<div class="table">
<div class="row">
<div class="cell">
<img src="http://placehold.it/600x400" />
</div>
<div class="cell">
<img src="http://placehold.it/300x400" />
</div>
</div>
</div>
.table {
display: table;
width: 100%;
}
.row {
display: table-row;
}
.cell {
display: table-cell;
}
img {
max-width: 100%;
}
要获得具有各种纵横比的图像相同的高度,可以通过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-sm-4">
<a href="product1.html">
<img src="image1.jpg" class="unim"/>
</a>
</div>
<div class="col-sm-4">
<a href="product2.html">
<img src="image2.jpg" class="unim"/>
</a>
</div>
<div class="col-sm-4">
<a href="product3.html">
<img src="image3.jpg" class="unim"/>
</a>
</div>
</div>
</div>
</section>
</body>
使用flex,它是为这种事情制成的。
.row {
display: flex;
justify-content:space-evenly;
}
img {
max-width: 100%;
}
<div class="row">
<div class="cell">
<img src="http://placehold.it/600x400" />
</div>
<div class="cell">
<img src="http://placehold.it/300x400" />
</div>
</div>
您想设置单元格内部的图像样式,并将其限制为单元格大小,因此需要更改:
img {
max-width:100%
}
to
.cell img {
height:50%;
width:auto /* This keeps the aspect ratio correct */
}
您仍然可以对桌子进行任何操作,但这将使图像保持相同的高度。