我正在尝试将两个画布堆叠在一起并使其成为双层画布。
我在这里看到了一个例子:
<div style="position: relative;">
<canvas id="layer1" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="layer2" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
但我想将两个画布都设置在屏幕的中心。如果我将 left
的值设置为常数,同时我改变屏幕的方向(就像我在 iPad 上做的那样),画布不会像它在屏幕上的作用那样保持在屏幕中间
<div align="center">
有人可以帮忙吗?
如果将左右两边都设置为零,并且左右边距设置为自动,则可以将绝对定位的元素居中。
position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;
如果您想在不知道元素宽度和高度的情况下居中对齐元素,请执行以下操作:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
例子:
*{ 边距:0;填充:0; } 部分{ 背景:红色;高度:100vh;宽度:100vw; } div{ 宽度:80vw;高度:80vh;背景:白色;位置:绝对;最高:50%;左:50%;变换:翻译(-50%,-50%); } Popup
left
额外的 50% 偏移量将外推父元素的宽度,将内容分解到下一行以避免溢出。但是,通过在元素中将 white-space
属性设置为 nowrap
,可以在使用此方法时保持内容内联。在 this JSFiddle 中尝试。
试试这个方法,对我来说很好用
position: absolute;
left: 50%;
transform: translateX(-50%);
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
你试过使用吗?:
left:50%;
top:50%;
margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */
不确定它是否会起作用,但值得一试......
次要编辑:添加了左边距部分,正如 Chetan 的评论所指出的那样......
margin-left: <negative half the width>
您所要做的就是确保您的父级 <div>
具有 position:relative
,并为要居中的元素设置高度和宽度。使用以下 CSS:
.layer {
width: 600px; height: 500px;
display: block;
position:absolute;
top:0;
left: 0;
right:0;
bottom: 0;
margin:auto;
}
https://output.jsbin.com/aXEZUgEJ/1/
将父 div 移动到中间
left: 50%;
top: 50%;
margin-left: -50px;
将第二层移到另一层之上
position: relative;
left: -100px;
不定期副业成功案例分享
left: 80px;
会将对象移动到中心右侧 40 像素 (!)。