首页 > 解决方案 > 如何使用双封面设置“背景尺寸”?

问题描述

我想设置一个background-size双盖像:

background-size:cover*200%; // not working
background-size:calc(cover*200%);  // not working
background-size:calc(cover); // not working

有可能做到吗?

我不想用javascript来做。多谢。

标签: css

解决方案


想法是考虑应用封面的另一个元素,并使这个元素大两倍。例如,您可以使用伪元素。

我保留溢出以查看结果:

.box {
  width:150px;
  height:150px;
  border:2px solid;
  margin:100px;
  position:relative;
  /* overflow:hidden;*/
  
}
.box:before {
  content:"";
  position:absolute;
  z-index:-1;
  top:50%;
  left:50%;
  background:var(--img) center/cover no-repeat;
  width:200%;
  height:200%;
  transform:translate(-50%,-50%);
  
  border:2px solid red;
}
<div class="box" style="--img:url(https://picsum.photos/200/350?image=1069)"></div>

与规模相同的想法:

.box {
  width:150px;
  height:150px;
  border:2px solid;
  margin:100px;
  position:relative;
  /* overflow:hidden;*/
  
}
.box:before {
  content:"";
  position:absolute;
  z-index:-1;
  top:0;
  left:0;
  background:var(--img) center/cover no-repeat;
  width:100%;
  height:100%;
  transform:scale(2);
  
  border:2px solid red;
}
<div class="box" style="--img:url(https://picsum.photos/200/350?image=1069)"></div>


推荐阅读