How to align absolutely positioned element to center?

后端 未结 7 1528
遇见更好的自我
遇见更好的自我 2020-12-22 17:51

I am trying to stack two canvas together and make it a double layers canvas.

I\'ve saw an example here:

&l
相关标签:
7条回答
  • 2020-12-22 18:21

    try this method, working fine for me

    position: absolute;
    left: 50%;
    transform: translateX(-50%); 
    
    0 讨论(0)
  • 2020-12-22 18:23

    All you have to do is,

    make sure your parent DIV has position:relative

    and the element you want center, set it a height and width. use the following 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/
    
    0 讨论(0)
  • 2020-12-22 18:24

    Have you tried using?:

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

    Not sure if it'll work, but it's worth a try...

    Minor edit: Added the margin-left part, as pointed out on the comments by Chetan...

    0 讨论(0)
  • 2020-12-22 18:31
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    
    0 讨论(0)
  • 2020-12-22 18:32

    Move the parent div to the middle with

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

    Move the second layer over the other with

    position: relative;
    left: -100px;
    
    0 讨论(0)
  • 2020-12-22 18:38

    If you want to center align an element without knowing it's width and height do:

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

    Example:

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

    0 讨论(0)
提交回复
热议问题