纯css实现响应式卡片
背景
卡片布局是开发过程中比较常见的样式,除了实现基本布局之外,还需要保证:
-
根据屏幕宽度进行自适应;
-
图片放缩的宽高比固定为16:9;
最终效果
大、中、小屏可以根据UI规定的断点调整,这里只是示例。
大屏
中屏
小屏
从效果图可以看到,无论是一行多少个,图片的宽高比始终是16:9,这样保证了用户在使用不同屏幕查看的时候效果都是合适的。
实现细节
1、自适应
利用element-ui自带的布局组件,通过设置响应式布局尺寸,实现最终效果。
2、图片比例保持16:9
// dom部分
<div class="scale">
<img src="xxx" class="item"/>
</div>
// css部分
.scale {
width: 100%;
padding-bottom: 56.25%; // 9/16 = 56.25%
height: 0;
position: relative;
}
.item {
width: 100%;
height: 100%;
position: absolute;
}
完整代码
<template>
<div class="container">
<el-container>
<el-header>Header</el-header>
<el-container>
<el-aside width="200px">Aside</el-aside>
<div class="main">
<el-row :gutter="10">
<el-col
:xs="24"
:sm="12"
:md="8"
:lg="6"
:xl="6"
v-for="(item, index) in new Array(20)"
:key="index"
>
<div class="card">
<div class="scale">
<el-image
class="item"
src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
fit="cover"
>
</el-image>
</div>
<div>标题</div>
</div>
</el-col>
</el-row>
</div>
<el-aside width="200px">Aside</el-aside>
</el-container>
</el-container>
</div>
</template>
<script>
export default {
name: "TestCardLayout",
data() {
return {};
}
};
</script>
<style>
.container > .el-container {
min-height: 100vh;
}
.el-header,
.el-footer {
background-color: #b3c0d1;
color: #333;
text-align: center;
line-height: 60px;
}
.el-aside {
background-color: #d3dce6;
color: #333;
text-align: center;
line-height: 200px;
}
.el-col {
border-radius: 4px;
}
.bg-purple-dark {
background: #99a9bf;
}
.bg-purple {
background: #d3dce6;
}
.bg-purple-light {
background: #e5e9f2;
}
.grid-content {
border-radius: 4px;
min-height: 36px;
}
.card {
background-color: #eee;
margin-bottom: 10px;
}
.scale {
width: 100%;
padding-bottom: 56.25%;
height: 0;
position: relative;
}
.item {
width: 100%;
height: 100%;
background-color: aquamarine;
position: absolute;
}
.main {
padding: 12px;
width: calc(100vw - 400px);
}
</style>