【问题标题】:How to center div based on anchor point of nested element如何根据嵌套元素的锚点使div居中
【发布时间】:2019-09-10 17:33:43
【问题描述】:

我有一个复杂的交互式 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 应进行缩放以覆盖整个视口,同时保持黑盒位于中心。

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

【问题讨论】:

  • 欢迎来到 StackOverflow!为了让我们更好地帮助您,您能否更新您的问题,以便它显示您的现有代码并在 @987654323 中详细说明任何失败的 attempts made so far @,并清楚地说明您想要的结果是什么。有关详细信息,请参阅有关 how to ask good questionstake the tour of the site 的帮助文章。
  • 你能提供代码示例@ruscandino-hanákana
  • 我真的不知道从哪里开始,添加了我到目前为止的内容。

标签: javascript html css centering anchorpoint


【解决方案1】:

试试这个:

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%);
}

【讨论】:

    【解决方案2】:

    要使矩形居中,您需要将其偏移一半widthheight。在这种情况下,您可能需要平移矩形。这样做:

    html,
    body {
    	margin: 0;
    	padding: 0;
    	overflow: hidden;
    	width: 100%;
    	height: 100%
    }
    <svg width="100%" height="100%">
    	<rect width='100%' height='100%' x="0" y="0" fill="yellow" />
    	<rect width='100' height='100' x="50%" y="50%" transform="translate(-50,-50)" fill="green" />
    </svg>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-15
      • 2011-09-12
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 2019-10-12
      • 2014-09-18
      • 1970-01-01
      相关资源
      最近更新 更多