CSS问题:点击DIV时背景图自动放大,需取消该效果
解决点击
.image-accordion元素时背景图放大的问题 问题分析
你遇到的背景图放大并非background-size或background-position属性导致,而是点击时添加的.clicked类修改了flex-grow值,使容器本身尺寸变大——由于你设置了background-size: contain,背景图会自适应容器尺寸,因此容器放大后背景图也随之被撑大。
解决方案
方案1:阻止容器尺寸变化(推荐)
直接移除.clicked类中所有flex-grow的特殊设置,让点击时容器保持原有尺寸,背景图自然不会放大:
.image-accordion{ background-size: contain; flex-grow: 1; background-position: center center; margin-bottom: 2px; transition: flex-grow 0.7s ease-in-out; @include respond-to(large){ height: 600px; margin-right: 4px; } &:last-child{ margin-bottom: 0px; @include respond-to(large){ margin-right: 0px; } } &.clicked{ // 设为和默认值一致的1,或直接删除该属性 flex-grow: 1; @include respond-to(large){ flex-grow: 1; } } }
如果不需要点击时的过渡动画,也可以把transition属性里的flex-grow字段删掉。
方案2:保持容器尺寸变化但固定背景图大小
若需要点击时容器仍能放大,但背景图保持原有尺寸,可将background-size改为固定值,比如auto(保留图片原始尺寸)或具体像素值:
.image-accordion{ background-size: auto; // 替换原有的contain flex-grow: 1; background-position: center center; margin-bottom: 2px; transition: flex-grow 0.7s ease-in-out; @include respond-to(large){ height: 600px; margin-right: 4px; } &:last-child{ margin-bottom: 0px; @include respond-to(large){ margin-right: 0px; } } &.clicked{ flex-grow: 2.8; @include respond-to(large){ flex-grow: 4.57; } } }
也可使用background-size: cover让背景图铺满容器但不拉伸(会裁剪图片),根据实际需求选择。
内容的提问来源于stack exchange,提问作者Pascual Ordiñana
相关产品推荐
相关产品推荐

