如何将绝对位置与中心alignment?

我正在尝试将两个canvas叠在一起,使其成为双层canvas。

我在这里看到一个例子:

<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> 

但是我想在屏幕的中心设置两个canvasalignment。 如果我将“左”的值设置为一个常数,而我改变了屏幕的方向(就像我在iPad上做的一样),canvas将不会像屏幕中间一样保持在屏幕中间

 <div align="center"> 

任何人都可以请帮忙?

如果将左右两个都设置为零,并且左右边距为自动,则可以将绝对定位的元素居中。

 position:absolute; left:0; right:0; margin-left:auto; margin-right:auto; 

如果你想中心alignment一个元素而不知道它的宽度和高度:

 position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); 

例:

 *{ margin:0; padding:0; } section{ background:red; height: 100vh; width: 100vw; } div{ width: 80vw; height: 80vh; background: white; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } 
 <section> <div> <h1>Popup</h1> </div> </section> 

你尝试过吗?:

 left:50%; top:50%; margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */ 

不知道它是否会工作,但值得一试…

小编辑 :增加了边界左边的部分,正如在Chetan的评论中指出的那样…

你所要做的就是,

确保你的父母DIV有位置:亲戚

和你想要的元素中心,设置它的高度和宽度。 使用下面的CSS

 .layer { width: 600px; height: 500px; display: block; position:absolute; top:0; left: 0; right:0; bottom: 0; margin:auto; } http://jsbin.com/aXEZUgEJ/1/ 
 position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; 

将父div移到中间

 left: 50%; top: 50%; margin-left: -50px; 

将第二层移到另一层

 position: relative; left: -100px; 

简单地使用:我什么也不做,不知道为什么,但是大部分的东西不能用于html5

 <html> <body> <div style="margin-left:25%"> // </div> </body> </html>