如何将绝对位置对齐到中心?

Pau*_*ing 88 css html5-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>
Run Code Online (Sandbox Code Playgroud)

但我想将两个画布对齐设置在屏幕的中心.如果我将'left'的值设置为常量,当我更改屏幕的方向时(因为我在iPad上执行aps),画布将不会像屏幕中间一样保留在屏幕中间

<div align="center">
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?

And*_*rew 192

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

position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;
Run Code Online (Sandbox Code Playgroud)

  • 备注:仅在样式元素具有给定的宽度时才有效。(px或%) (4认同)
  • 我认为在这种情况下没有必要。 (3认同)

Vin*_*ana 74

如果要在不知道宽度和高度的情况下居中对齐元素,请执行以下操作:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Run Code Online (Sandbox Code Playgroud)

例:

*{
  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%);
}
Run Code Online (Sandbox Code Playgroud)
<section>
  <div>
    <h1>Popup</h1>
  </div>
</section>
Run Code Online (Sandbox Code Playgroud)

  • 这是对我有用的一个答案。谢谢! (2认同)

sub*_* pm 22

试试这个方法,对我来说很好用

position: absolute;
left: 50%;
transform: translateX(-50%); 
Run Code Online (Sandbox Code Playgroud)


Del*_*man 15

你试过用过吗?:

left:50%;
top:50%;
margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */
Run Code Online (Sandbox Code Playgroud)

不确定它是否有用,但值得一试......

次要编辑:添加了左边缘部分,正如Chetan的评论所指出的那样......

  • @PaulLing`margin-left:<负半宽>` (2认同)

Mih*_*anu 10

position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
Run Code Online (Sandbox Code Playgroud)


STE*_*EEL 7

你所要做的就是,

确保你的父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/
Run Code Online (Sandbox Code Playgroud)

  • 只有对我有用的解决方案.父设置为flex,flex-grow和overflow.对于比父母大的图像,将孩子定位在框架外.它似乎没有意识到父母的宽度.现在已经修好了.十分感谢! (2认同)