如何将背景图像的特定 (x,y) 点居中到包含它的 CSS 元素的已定义 (x',y') 坐标?

How to center an specific (x,y) point of a background image to a defined (x',y') coordinates of the CSS element that contains it?

我读到要在 CSS 中的容器块中放置背景图像,您可以使用 background-position 属性。你可以给它加上标签,比如 top-right-bottom-left-center 或 css 单位,主要是百分比。它的行为方式有点像这样:

background-position: 25% 25%, 将背景图像的 (25%, 25%) 点从右上边缘居中到 [= 的 (25%, 25%) 点37=] 包含该背景的元素。

那么如果我想把背景图片的(50% 50%)点居中到容器的(0,0)点,怎么实现呢?

我知道我可以用伪元素 (:before, :after) 来做,但是有没有数学计算可以帮助我使用背景 属性 来完成这项工作?不幸的是,我还没有找到 属性 这样的注册表点,可以让我放置我想用作背景中心的点(background-origin 尽管关闭意味着它用于我发现的完全不同的东西。

这个问题是关于任何情况的,但作为一个例子,我分享了一个快速简单的片段,以使其更加形象化。

顺便说一下,我正在努力寻找我能找到的最灵敏的解决方案。如果我们可以假设我不知道背景图像的确切尺寸,那么如果我以后将该图像更改为另一个不同尺寸的图像,它会保持在同一个位置的中心,这会好得多。这意味着我更喜欢 % 而不是 px。

.foo {
  margin: 0 auto;
  width: 400px;
  height: 300px;
  background: url('https://source.unsplash.com/random/200x200') no-repeat, blue
}
 <! -- Let's supose I would like to center the (50%, 50%) of that image placeholder at the (0,0) of the container div. -- >

<div class='foo'></div>

提前致谢

由于您知道背景图片的大小 (200x200),因此您可以使用这些像素值的一半作为背景位置的负值,以使图片的中心恰好位于其背景的左上角div 元素。在你的情况下,那将是 background-position: -100px -100px;:

.foo {
  margin: 0 auto;
  width: 400px;
  height: 300px;
  background: url('https://source.unsplash.com/random/200x200') no-repeat, blue;
  background-position: -100px -100px;
}
<! -- Let's supose I would like to center the (50%, 50%) of that image placeholder at the (0,0) of the container div. -- >

<div class='foo'></div>

第二个版本:如果您使用常规图像而不是背景图像,则可以在其上使用 transform: translate(-50%, -50%);,在父图像上使用 overflow: hidden。这样使用百分比值的方法就可以了。

但是,在这种情况下,如果您还需要容器其余部分的背景颜色,则向主内容添加内容会变得更加复杂 div - 您必须为容器的其余部分添加一个绝对定位的元素那。

.foo {
  margin: 0 auto;
  width: 400px;
  height: 300px;
  background: #bbf;
  overflow: hidden;
  position: relative;
}

.foo>img {
  transform: translate(-50%, -50%);
}

.foocontent {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
<div class='foo'>
  <img src="https://source.unsplash.com/random/200x200" />
  <div class="foocontent">
    Here's some text and even some more text to demonstrate how text content could be placed above the image that serves as a background here.
  </div>
</div>

百分比单位不能用于偏移背景图像,因为它定义了相对于其容器的整个图像点。 你可以做的是定义图像的大小和位置,它使用像素单位。

使用背景shorthand:

background: url(img) -100px -150px / 200px 300px;
body {
    background: url(https://images.unsplash.com/photo-1519940640025-75fdf32010d7?ixlib=rb-1.2.1&auto=format&fit=crop&w=1234&q=80) -100px -150px / 200px 300px no-repeat pink;
}