当img占不满div时,图片居中显示,两侧加当前图片模糊效果

@TOC

实现效果

当img占不满div时,图片居中显示,两侧加当前图片模糊效果_ide

解决方案

方案一:使用 CSS 伪元素实现模糊背景效果

.video_list {.text_pics_box_item_img_box {width: 200px;height: 100px;position: relative;overflow: hidden;display: flex;align-items: center;justify-content: center;&::before {content: '';position: absolute;top: 0;left: 0;width: 100%;height: 100%;background-image: var(--bg-image);background-size: cover;background-position: center;background-repeat: no-repeat;filter: blur(10px);transform: scale(1.1);z-index: 1;}::v-deep {.el-image {position: relative;z-index: 2;max-width: 100%;max-height: 100%;width: auto;height: auto;}}}
}

然后在模板中为 el-image 添加样式绑定:

<div class="text_pics_box_item_img_box"v-if="item.video_cover_imgs.length":style="{'--bg-image': `url(${item.video_cover_imgs[0]})`}"><el-image :src="item.video_cover_imgs[0]" fit="contain"></el-image>
</div>

方案二:使用额外的背景元素

.video_list {.text_pics_box_item_img_box {width: 200px;height: 100px;position: relative;overflow: hidden;.blur-background {position: absolute;top: 0;left: 0;width: 100%;height: 100%;background-size: cover;background-position: center;background-repeat: no-repeat;filter: blur(10px);transform: scale(1.1);z-index: 1;}::v-deep {.el-image {position: relative;z-index: 2;max-width: 100%;max-height: 100%;width: auto;height: auto;}}}
}

对应的模板代码:

<div class="text_pics_box_item_img_box"v-if="item.video_cover_imgs.length"><div class="blur-background" :style="{backgroundImage: `url(${item.video_cover_imgs[0]})`}"></div><el-image :src="item.video_cover_imgs[0]" fit="contain"></el-image>
</div>

方案三:使用双层图片结构

.video_list {.text_pics_box_item_img_box {width: 200px;height: 100px;position: relative;overflow: hidden;.blur-img {position: absolute;top: 0;left: 0;width: 100%;height: 100%;::v-deep {.el-image__inner {width: 100%;height: 100%;object-fit: cover;filter: blur(10px);transform: scale(1.1);}}}.main-img {position: relative;z-index: 2;max-width: 100%;max-height: 100%;::v-deep {.el-image__inner {max-width: 100%;max-height: 100%;width: auto;height: auto;object-fit: contain;}}}}
}

对应的模板代码:

<div class="text_pics_box_item_img_box"v-if="item.video_cover_imgs.length"><div class="blur-img"><el-image :src="item.video_cover_imgs[0]"></el-image></div><div class="main-img"><el-image :src="item.video_cover_imgs[0]"></el-image></div>
</div>

推荐方案

推荐使用方案一,因为它:
  1. 代码简洁,只需一个额外的伪元素
  2. 性能较好,不需要额外的DOM元素
  3. 易于维护和修改
  4. 使用CSS变量动态设置背景图,灵活性高
关键点解释:
  1. filter: blur(10px) 创建模糊效果
  2. transform: scale(1.1) 防止模糊边缘出现白边
  3. z-index确保清晰图片在模糊背景之上
  4. object-fit: contain 保持图片比例完整显示
  5. 使用CSS变量动态设置背景图片路径