首页 > 解决方案 > 如何根据嵌套元素的锚点使div居中

问题描述

我有一个复杂的交互式 SVG 图形。在该图形中有一个特定的图标,假设它是信息图中的特定人物图标。此外,SVG 为 2000x2000 像素。这意味着在桌面(横向布局)上,它可能需要从顶部和底部剪掉一些以适应屏幕。在移动设备(纵向模式)中,它需要从右侧和左侧剪掉一些。鉴于此,我希望 SVG 以该人为中心,并在横向模式下剪辑顶部/底部,在纵向模式下剪辑左/右。这实现了两个目标:

  1. 图像始终以那个人为中心。
  2. 图像总是完全填满可用空间,无论是横向还是纵向模式。

想知道如何做到这一点。如果它必须用 JavaScript 完成,或者如果它可以纯粹用 CSS 完成。

此外,这个 SVG 不能加载到 CSS 的背景图像中,因为它是交互式的。它是普通的 SVG。

为了简化问题,我们可以说我们有<div>一堆嵌套元素。我们希望这个 div 基于它包含的一些嵌套元素居中。因此,这似乎需要某种 JavaScript。也就是说,在窗口调整大小或方向更改时,获取我们想要居中的元素的偏移量,然后弄清楚如何将其调整为居中,然后从中找出如何调整 parent.parent.parent ......等等。直到您到达要在该点锚定的主包装器 div。然后我们将那个 div 移动多少。所以看起来这需要JavaScript,但我不知道,也许有一种方法可以用纯CSS来完成。

想知道是否可以演示如何在 JS 或 CSS 中执行此操作。

这是我到目前为止所拥有的。

// the box should be centered in the screen
<!doctype html>
<html>
  <head>
    <style>
      html, body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        width: 100vw;
        height: 100vh;
      }
      
      svg {
        display: block;
      }

      @media (orientation: landscape) {
        svg {
          width: 100vw;
          height: auto;
        }
      }

      @media (orientation: portrait) {
        svg {
          width: auto;
          height: 100vh;
        }
      }
    </style>
  </head>
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2000 2000">
      <rect width='100' height='100' x="1000" y="1000" />
    </svg>
  </body>
</html>

请注意(https://imgur.com/PnugEin)在移动设备上它没有正确填充空间。黑盒应始终位于中心,整个 SVG 应缩放以覆盖整个视口,同时将黑盒保持在中心。

更新:好的,通过添加媒体查询来解决“填充视口”问题。最后一件事是如何根据矩形/锚点将其居中。

标签: javascripthtmlcsscenteringanchorpoint

解决方案


尝试这个:

svg[viewBox="0 0 2000 2000"] {
    /* center the SVG in the viewport */
    position: absolute;
    top: -50%;
    bottom: -50%;
    left: -50%;
    right: -50%;
    margin: auto;

    /* offsets from center of SVG. In the example given, it's (100/2)/2000 and then multiply by 100 because it's a percentage */
    -webkit-transform: translate(-2.5%,-2.5%);
    transform: translate(-2.5%,-2.5%);
}

推荐阅读