search

Home  >  Q&A  >  body text

transform - css3 translate 的水平垂直居中问题求解

transform: translate(50%, 50%)

为什么能够使一个元素水平垂直居中?

黄舟黄舟2778 days ago647

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-04-17 11:40:22

    Writing like this does not center an element horizontally and vertically. It can only make the element translate half of its own width in the positive direction of the x-axis and y-axis at the current position.

    I answered a question before. You can take a look at it. It may be of some help.

    translate

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 11:40:22

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <!--author:Vace_Vlm(ocdo@qq.com),create:2016年5月21日 下午10:45-->
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>title</title>
        <style>
            *{
                padding: 0;margin: 0;
            }
            html,body{
                width:100%;
                height:100%;
            }
            .box{
                position:relative;
                top:50%;
                left:50%;
                width:200px;
                height:200px;
                background:red;
                transform:translate(-50%,-50%);
                transform-origin:50% 50%;
            }
        </style>
    </head>
    <body>
        <p class="box"></p>
    </body>
    </html>

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 11:40:22

    Writing like this cannot be directly centered, but can be positioned, and then left:50%; At this time, the positioning origin is the positioning element of the parent layer, and then use translateX(-50%); at this time, it is moved to the left relative to the element itself. Half, the final effect is exactly centered.

    reply
    0
  • Cancelreply