使两个图像具有相同的高度而无需硬编码? [英] Make two images same height without hardcoding?

查看:66
本文介绍了使两个图像具有相同的高度而无需硬编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有两个图像.我确切地拥有这两个img元素的宽度.这两个元素及其容器之间的装订线正是我想要的.

Here I have two images. I have the widths of these two img elements exactly how I want it. The gutter between these two elements and their container is exactly how I want it as well.

应用 vertical-align:top 之后,我注意到这两个图像均根据源图像的纵横比自动确定其自身的高度.如您所见,这意味着图像最终具有相同的宽度(这是我明确定义的),但高度却相差约十几个像素:

After applying vertical-align: top, I noticed that both of these images automatically determine their own height based on the aspect ratio of the source image. As you can see this means the images end up having the same widths (which I defined explicitly) but different heights by a matter of a dozen pixels or so:

我想知道是否有办法在不切换成背景图像的情况下给这两个图像相同的高度.另外,如果此图像馈送是动态的",我如何在不知道所讨论图像的纵横比的情况下明确定义高度?

I was wondering if there is a way to give both of these images the same height without switching them to be background-image's. Also, if this image feed is 'dynamic' how could I explicitly define the height while not knowing the aspect ratio of the image in question?

推荐答案

因此,问题是,如果在两个大小不同的图像上将宽度和高度设置为相同,则至少其中一个会失真.

So the problem is that if you set the width and height the same on two differently sized images, at least one of them will be distorted.

您可以很容易地解决此问题,只要图像的尺寸相对相似即可.想法是,用div包围图像,并为div赋予高度和宽度,而不是图像的高度和宽度.然后给它CSS overflow:hidden; ,它将裁剪掉图像的多余部分.您可能还需要给它 display:inline-block; 以使div彼此相邻.

You could quite easily fix this, as long as the images are relatively similar in size. The idea is, you surround the image with a div and give the div the height and width instead of the image. Then give it the CSS overflow: hidden; and it will crop off the extra bit of the image. You may also need to give it display: inline-block; to get the div's next to each other.

div {
  display: inline-block;
  height: 200px;
  width: 200px;
  overflow: hidden;
}

<div>
  <img src="http://via.placeholder.com/200x200">
</div>
<div>
  <img src="http://via.placeholder.com/200x240">
</div>

或者如果您希望图像垂直居中:

Or if you want the image vertically centered:

div {
  display: inline-block;
  height: 200px;
  width: 200px;
  overflow: hidden;
  position: relative;
}
img {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

<div>
  <img src="http://via.placeholder.com/200x200">
</div>
<div>
  <img src="http://via.placeholder.com/200x240">
</div>

这篇关于使两个图像具有相同的高度而无需硬编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆