图像尺寸有3个案例:
image width > image height
image width < image height
image width == image height
我需要使用img
来显示div
内的图片。
<div class="container">
...
<img class="scale-and-fill" src="..." />
...
</div>
如何:
下面的CSS类应该输入什么?
.container {
...
}
.scale-and-fill {
...
}
包含屏幕截图以清楚地说明我的问题。
答案 0 :(得分:0)
你最好的选择是缩减规模。让我们假设高度不合适。如果是这种情况,下面的内容将会很有用
.container {
width: 250px; /* Adjust as needed */
height: 200px; /* Must be a litle smaller than the images original height */
overflow: hidden;
}
.scale-and-fill {
width: 100%;
height: auto; /* The image will now fit since
.container is smaller than the original size */
}
查看有关图像控制的本教程
答案 1 :(得分:0)
您可以设置.container的宽度/高度,例如:
.container {
width: 300px;
height: 250px;
}
并设置图像样式:
.scale-and-fill {
display: block;
width: 100%;
max-width: 100%;
max-height: 100%;
}
答案 2 :(得分:0)
你不能只用css做这件事。您描述的问题有以下形式:
IF (image-dimensions) THEN (css-rule)
为此你需要编写脚本。
答案 3 :(得分:0)
你需要在不同的情况下应用两个不同的类:
.scale-and-fill1 {
width: 100%;
height: auto;
position: relative;
}
.scale-and-fill2 {
width: auto;
height: 100%;
position: relative;
}
.container {
overflow: hidden;
}
这应该保持比例,但是为了获得正确的课程你应该使用一点点javascript。
我会添加这个jquery javascript:
$(document).ready(
$('.container img').each(function() {
var ratio = $(this).width() / $(this).height();
if (ratio > 1) {
$(this).attr('çlass','.scale-and-fill2');
$(this).attr('left',$('. container').width()/2 - $(this).width() / 2);
} else {
$(this).attr('çlass','.scale-and-fill1');
$(this).attr('top',$('. container').height()/2 - $(this).height() / 2);
}
});
)
答案 4 :(得分:0)
使用您选择的宽高比。 16/9用于高清显示器。
.container {
width: 300px;
height: 250px;
}
.scale-and-fill {
width: 100%;
height: unset;
object-fit: cover;
}
@media (max-aspect-ratio: 16/9) {
.scale-and-fill {
width: unset;
height: 100%;
}
}