H5Skills icon indicating copy to clipboard operation
H5Skills copied to clipboard

常用商品组占位图实现

Open liqinuo opened this issue 7 years ago • 1 comments

常见商品组占位图情况:

.cover {
    position: relative;
    height: 0;
    overflow: hidden;
    padding-top: 100%;
    img {
        display: block;
        width: 100%;
        height: auto;
        position: absolute;
        top: 0;
        left: 0;
    }
}

如果是其他比例的商品图与容器比例不符,可以这样处理:

.cover {
    position: relative;
    height: 0;
    overflow: hidden;
    padding-top: 100%;
    img {
        display: block;
        position: absolute;
        top: 50%;
        left: 50%;
        max-width: 100%;
        max-height: 100%;
        transform: translate(-50%,-50%);
    }
}

如果商品图需要完全铺满,可以进一步这样处理:

需要配合脚本判断图片宽高,宽大于高时使用类名 .full_h,高大于宽时使用类名 .full_w

.cover {
    position: relative;
    height: 0;
    overflow: hidden;
    padding-top: 100%;
    img {
        display: block;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        &.full_w {width: 100%;}
        &.full_h {height: 100%;}
    }
}

抛开兼容问题,我们还有一个更适合的属性 object-fit,可以这样处理:

.cover {
    position: relative;
    height: 0;
    overflow: hidden;
    padding-top: 100%;
    img {
        display: block;
        position: absolute;
        top: 0;
        left: 0;
        object-fit: contain 或 cover;
    }
}

object-fit 兼容表:

liqinuo avatar Jul 04 '17 12:07 liqinuo

mark

sir-ran avatar Feb 02 '21 08:02 sir-ran