如何将元素定位在视口左边缘之外?

How to position element just beyond the left edge of the viewport?

我有一个元素,其宽度是固定的 px 值或百分比。我希望其边界框的右侧位于屏幕(或视口)的 x 坐标 −1,因此它的右侧接触屏幕左侧 —— 元素会变得隐形。

是否有一个值可以用于 CSS rightleft 属性 并且适用于百分比和固定 px 宽度或者是还有其他方法可以实现吗?

试试这个:

.fixed {
    position: fixed;
    top: 1em;
    left: 1em;
}

这组 CSS 规则适用于:

/* These rules position the element just beyond the left edge of the viewport. */
.positioned {
  position: absolute;
  left: 0;
  transform: translateX(-100%);
}

/* You can open your developer tools (Right Click → Inspect Element) and change the `-100%` from above to see this box. */
.positioned {
  width: 100px;
  height: 100px;
  background: rebeccapurple;
  padding: 4px;
  color: white;
}
<div class="positioned">
  I’m on the left.
</div>

position: absoluteleft: 0 将元素放在左边缘,但在视口内。那么 transform: translateX(-100%) 就是将你的元素向左移动的规则,正好是它的宽度。

这是有效的,因为如果 translatetranslateXtranslateY 的参数是百分比,那么这些百分比与 元素的 宽度和高度。对于 leftright 等其他属性,它们与 父级的 宽度和高度相关。因此,leftright 不能在所有情况下用于这种 - 相对或固定宽度 -,这就是为什么您的原始问题的答案是:没有,没有价值对于这两个属性来实现这一点。可能有某种形式的诡计来实现这一点,但 CSS3 的 transform 函数(或个别 — 尽管不太兼容 — 属性)使这很容易。


如果您 运行 片段,您应该 什么都看不到 。如果您使用 browser console (dev tools)(点击 F12)并检查代码段的结果并找到 <div class="positioned">,您将看到: