Css 如何拉伸img元件以达到其div的全高
我有两个div,包括不同的纵横比图像。我需要image2来填充它的div(container2),这样它们的响应高度就相同了 我试图设置对象匹配,但不起作用。我不想为img元素设置显式高度,因为这不会使设计变得灵活。我尝试这样做是为了能够使一个画廊的图像都有相同的高度,无论高宽比是什么Css 如何拉伸img元件以达到其div的全高,css,Css,我有两个div,包括不同的纵横比图像。我需要image2来填充它的div(container2),这样它们的响应高度就相同了 我试图设置对象匹配,但不起作用。我不想为img元素设置显式高度,因为这不会使设计变得灵活。我尝试这样做是为了能够使一个画廊的图像都有相同的高度,无论高宽比是什么 。容器的容器{ 显示器:flex; } .集装箱1{ 边框:2个红色实心; 宽度:300px; 右边距:20px; } .集装箱2{ 边框:2个红色实心; 宽度:40%; } img{ 宽度:100%; 显示:
。容器的容器{
显示器:flex;
}
.集装箱1{
边框:2个红色实心;
宽度:300px;
右边距:20px;
}
.集装箱2{
边框:2个红色实心;
宽度:40%;
}
img{
宽度:100%;
显示:块;
}
JS-Bin
将img的答案分为两个部分。将img元素设置为绝对位置。将第一个div父级设置为相对位置,将padding top设置为所需的百分比,以便根据需要保持所需的纵横比。将第二个div父对象设置为所需的宽度,并将其向左浮动
代码如下所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Setting the same height on 2 different aspect ratio images </title>
<style>
.aspect-ratio-outer {
width: 50%; /* Any width here applicable according to the design */
float: left; /* to align the containers of the images horizontally */
}
.aspect-ratio-inner{
padding-top: 56.25%; /* 19:6 aspect ratio */
position: relative; /* to allow absolute position for the child img */
}
img {
width: 100%; /* in order not to go out of its container */
display: block;
object-fit: cover; /* to keep the aspect ratio of the source image not the aspect ratio we design here */
height: 100%; /* in order to fill its container height which is the padding-top we set */
}
.aspect-ratio-inner .image {
position: absolute; /* To make it always appear in its container */
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div class="aspect-ratio-outer">
<div class="container1 aspect-ratio-inner">
<img src="https://images.unsplash.com/photo-1502307100811-6bdc0981a85b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=626&q=80" alt="" class="image">
</div>
</div>
<div class="aspect-ratio-outer">
<div class="container2 aspect-ratio-inner">
<img src="https://cdn.pixabay.com/photo/2015/12/01/20/28/road-1072823__340.jpg" alt="" class="image">
</div>
</div>
</body>
</html>
在两个不同纵横比的图像上设置相同的高度
.宽高比{
宽度:50%;/*此处根据设计适用的任何宽度*/
float:left;/*用于水平对齐图像的容器*/
}
.长宽比内部{
填充顶部:56.25%;/*19:6纵横比*/
位置:相对;/*允许子img的绝对位置*/
}
img{
宽度:100%;/*以避免从容器中流出*/
显示:块;
object fit:cover;/*以保持源图像的纵横比,而不是我们在此设计的纵横比*/
高度:100%;/*以填充其容器高度,即我们设置的填充顶部*/
}
.宽高比内部图像{
位置:绝对;/*使其始终显示在其容器中*/
排名:0;
左:0;
底部:0;
右:0;
}
.container2 img{height:100%}
使用这个。是的,它是这样工作的。但是,如果我移除flex效果并使用浮动水平对齐2个div,问题仍然存在。有什么区别@piyushjaindisplay:flex
将使两个容器的高度相等。@piyushjain说得对,谢谢。这似乎只适用于flex或grid,因为默认情况下,这些方法会将其项的高度拉伸到最大项的高度。如果您知道如何在只使用浮动的情况下解决问题,而不是使用浮动,为什么不能将图像显示为背景?所以背景尺寸:封面可以给你惊人的对齐效果。