我有一个元素,其宽度是固定像素或基于媒体查询的百分比。但我希望它的框边界的右侧在屏幕的x坐标-1处,因此其右侧触摸屏幕的左侧,但不可见。是否可以使用css规则right
或left
的值同时适用于百分比和固定像素宽度?
谢谢
这套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%)
是将元素精确按其宽度向左移动的规则。
这是有效的,因为如果transform: translateX(-100%)
,translate
和translateX
的参数是百分比,则它们与element's的宽度和高度有关,而不是与父项的宽度和高度有关(实际情况是这样)其他属性,例如translateY
)。
如果运行该代码段,您应该会看到nothing。如果您使用left
(点击browser console (dev tools))并查看摘要的结果并找到F12
,则会看到以下内容:
<div class="positioned">