裁剪然后拉伸背景图像以适合某个区域

时间:2019-01-14 21:55:59

标签: html css crop fill stretch

我有一个800像素宽,500像素高的图像,我希望先裁切一下。左侧x像素,右侧y像素,底部z像素,然后将其设置为1200像素宽,1000像素高的背景区域,其中x,y和z都不同。

我还试图使其不响应,以便它不会随着窗口大小的改变而缩放,因此不能设置background-size = covercontain。任何建议都将不胜感激,例如,如果我可以先裁剪图像,然后将其填充到我的区域。谢谢。

2 个答案:

答案 0 :(得分:0)

我认为如果没有一些棘手的javascript,您将无法实现。但是我在这里将其放入代码中,这样其他人可以更轻松地看一下-当您提出第一个问题时,这也是一件好事。

按原样,它使用background-position-x和-y来“裁剪”图像的一部分,然后,如果有一种足够的放大方法,您也可以裁剪掉另一端。 。

.container {
border: solid black 1px;
height: 1000px;
width: 1200px;
background-image: url(https://snag.gy/dL487F.jpg);
background-position-x: -100px;
background-position-y: -50px;
background-repeat: no-repeat;
}
<div class="container">

</div>

答案 1 :(得分:0)

您可以考虑将background-size与百分比和像素值结合使用以获得所需的内容:

.container {
  background-image:url(https://picsum.photos/800/600?image=1069);
  background-size:
    calc(100% + 100px + 200px) /*100% + x + y*/
    calc(100% + 50px); /*100% + z*/
  background-position:-100px 0; /*we shift by x*/
  background-repeat:no-repeat;
  
  width:1200px;
  height:1000px;
}
<div class="container">

</div>

您还可以添加CSS变量来轻松控制此变量:

.container {
  --x: 100px;
  --y: 200px;
  --z: 50px;
  background-image: url(https://picsum.photos/800/600?image=1069);
  background-size: calc(100% + var(--x) + var(--y)) calc(100% + var(--z));
  background-position: calc(-1 * var(--x)) 0;
  background-repeat: no-repeat;
  
  width: 1200px;
  height: 1000px;
}
<div class="container">

</div>