Html CSS保留纵横比,但填充父div
基本上,我有一个图像,我想用一个圆遮罩Html CSS保留纵横比,但填充父div,html,css,less,Html,Css,Less,基本上,我有一个图像,我想用一个圆遮罩 <div class="thumbnail-mask"> <img class="thumbnail-pic" src="/image.jpeg"> </div> 我已经知道了如何在父对象中垂直和水平居中放置图像 .thumbnail-pic { text-align: center; position: relative; top: 50%; -webkit-transform: translat
<div class="thumbnail-mask">
<img class="thumbnail-pic" src="/image.jpeg">
</div>
我已经知道了如何在父对象中垂直和水平居中放置图像
.thumbnail-pic {
text-align: center;
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
// width: 100%;
// height: auto;
height:auto;
width: 100%;
}
但现在的问题是高度和宽度
如果我尝试身高:100%;宽度:100%代码>纵横比已更改
如果高度>宽度,那么我想要宽度:100%;高度:自动代码>。如果宽度>高度,我希望高度:100%;宽度:自动
。这样,圆圈就完全填满了。但这似乎是不可能的。我尝试设置最小宽度:100%;最小高度:100%
但是如果不设置高度或宽度,图像太大。显示:内联块.thumbnail mask
中的code>应将
包裹在其内部
一种解决方案是使用jquery根据纵横比设置图像宽度和高度
$(document).ready(function () {
$("img").each(function () {
// Calculate aspect ratio and store it in HTML data- attribute
var aspectRatio = $(this).width() / $(this).height();
$(this).data("aspect-ratio", aspectRatio);
// Conditional statement
if (aspectRatio > 1) {
// Image is landscape
$(this).css({
height: "100%"
});
} else if (aspectRatio < 1) {
// Image is portrait
$(this).css({
width: "100%"
});
}
});
});
$(文档).ready(函数(){
$(“img”)。每个(函数(){
//计算纵横比并将其存储在HTML数据-属性中
var aspectRatio=$(this.width()/$(this.height());
数据(“纵横比”,aspectRatio);
//条件语句
如果(aspectRatio>1){
//图像就是风景
$(this.css)({
身高:“100%”
});
}否则如果(aspectRatio<1){
//图像就是肖像
$(this.css)({
宽度:“100%”
});
}
});
});
显然,对于纯css方法来说,这并没有那么优雅,但最终可能会更加可靠您是否使用了“最大高度”和“最大宽度”,但将特定宽度和高度设置为容器的维度?我想这就是我实现同样目标的原因。这基本上就是我现在要做的。但它确实减慢了浏览器的速度。特别是当我有一堆这样的图片,当它们呈现时会有一堆反应性的回调。好的,我明白你说的另一种方法是稍微调整html结构,将图片作为背景图片,然后使用封面。在我之前的评论中有一个微妙的联系
$(document).ready(function () {
$("img").each(function () {
// Calculate aspect ratio and store it in HTML data- attribute
var aspectRatio = $(this).width() / $(this).height();
$(this).data("aspect-ratio", aspectRatio);
// Conditional statement
if (aspectRatio > 1) {
// Image is landscape
$(this).css({
height: "100%"
});
} else if (aspectRatio < 1) {
// Image is portrait
$(this).css({
width: "100%"
});
}
});
});