如何在html中将元素设置在屏幕的左侧?

问题描述 投票:4回答:2

我有一个元素,其宽度是固定像素或基于媒体查询的百分比。但我希望它的框边界的右侧在屏幕的x坐标-1处,因此其右侧触摸屏幕的左侧,但不可见。是否可以使用css规则rightleft的值同时适用于百分比和固定像素宽度?

谢谢

html css
2个回答
7
投票

这套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%)是将元素精确按其宽度向左移动的规则。

这是有效的,因为如果transform: translateX(-100%)translatetranslateX的参数是百分比,则它们与element's的宽度和高度有关,而不是与父项的宽度和高度有关(实际情况是这样)其他属性,例如translateY)。


如果运行该代码段,您应该会看到nothing。如果您使用left(点击browser console (dev tools))并查看摘要的结果并找到F12,则会看到以下内容:

<div class="positioned">


1
投票

尝试一下:

The bounding box of the <div> can be seen just to the left of the snippet result.
© www.soinside.com 2019 - 2024. All rights reserved.