【问题标题】:Is there a way to position background image center to exact coordinates?有没有办法将背景图像中心定位到精确坐标?
【发布时间】:2020-11-21 18:44:10
【问题描述】:

我在正文中有一个背景图片,svg 普通圆圈。

在 background-position: 0%, 0% 这个圆圈出现在页面的左上角。 但我希望这个圆圈的 center 正好位于 0,0(左上角)并保持在那里,无论设备宽度如何。

我可以用负百分比或像素或 em/rem 手动将其居中,但当我更改浏览器宽度时它不会停留在那里。

谁能帮忙?

这是来自 codepen.io 的链接: https://codepen.io/sandro-bochorishvili/pen/KKMjezN

实际代码: css

body {
  overflow-y: scroll;
  height: 100vh;
  background-color:  hsl(185, 75%, 39%);
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url(https://svgshare.com/i/Rfg.svg),
                    url(https://svgshare.com/i/RgK.svg);
  background-position: -20rem -34rem, 72em 15em;

  background-repeat: no-repeat, no-repeat;
  padding: 0 2em 0 2em;
}

【问题讨论】:

  • 如果您以像素为单位指定偏移量,则它不应移动。可以加个sn-p吗?
  • 没错,假设background-size 设置为cover,图像可以根据可用空间在X 轴或Y 轴(或两者)上拉伸。但是,有很多方法可以做到这一点,因此我们需要一个真实的例子来提出最可行的解决方案。
  • 感谢您的回复!其实我想通了,但我需要在右下角做同样的事情,但这是一个棘手的问题,像素不起作用,圆圈向右移动并从屏幕上消失(当宽度减小时)
  • 这是来自 codepen.io 的链接:codepen.io/sandro-bochorishvili/pen/KKMjezN

标签: html css coordinates background-image background-position


【解决方案1】:

要结合相对尺寸和绝对尺寸,您可以使用calc,在您的情况下为 background-position: -20rem -34rem, calc(100% + 20rem) calc(100% + 34rem);

body {
  overflow-y: scroll;
  height: 100vh;
  background-color:  hsl(185, 75%, 39%);
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url(https://svgshare.com/i/Rfg.svg),
    url(https://svgshare.com/i/RgK.svg);
 background-position: -20rem -34rem, calc(100% + 20rem) calc(100% + 34rem);

  background-repeat: no-repeat, no-repeat;
  padding: 0 2em 0 2em;
}

【讨论】:

    猜你喜欢
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    相关资源
    最近更新 更多