【问题标题】:How to position element just beyond the left edge of the viewport?如何将元素定位在视口左边缘之外?
【发布时间】:2020-04-11 02:34:45
【问题描述】:

我有一个元素的宽度是固定的px 值或百分比。我希望其边界框的右侧位于屏幕(或视口)的 x 坐标 -1 处,因此它的右侧接触到屏幕的左侧 — 元素将变为不可见这个。

我可以为 CSS right 或 left 属性使用一个值,该值适用于百分比和固定 px 宽度,还是有其他方法可以实现这一点?

【问题讨论】:

  • 显示您尝试过的相关代码,最好使用 jsfiddle/stack sn-p

标签: html css css-position


【解决方案1】:

这组 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: absolute 和left: 0 将元素放置在左边缘,但在视口内。那么transform: translateX(-100%) 就是将元素向左移动宽度的规则。

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


如果您运行 sn-p,您应该会看到 nothing。如果你使用browser console (dev tools)(点击F12)并检查sn-p的结果并找到&lt;div class="positioned"&gt;,你会看到:

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 这符合问题的标题,但不符合对象应该隐藏在屏幕左侧的描述。
    猜你喜欢
    • 1970-01-01
    • 2014-10-02
    • 2013-01-02
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多