居中布局

2019-01-13  本文已影响0人  废废_siri

水平居中

--行内元素
text-align:center
--块元素
margin: 0 auto
flex + justify-content:center
absolute + transform

垂直居中

line-height:容器的高度(height);
flex + align-items:center
absolute + transform 

垂直水平居中

已知元素的宽高的居中布局

定位居中布局

选择器{
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            margin: auto;
}

盒模型居中布局

选择器{
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -50px;(元素width的一半)
            margin-top: -50px;(元素height的一半)
            width:100px;
            height:100px;
}

图片的垂直水平居中(利用基线)

 <style>
        #wrap{
            width: 300px;
            height: 300px;
            border: 1px solid;

            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -150px;
            margin-top: -150px;
            text-align: center;
        }

        #wrap img{
            width: 200px;
            height: 200px;
            vertical-align: middle;
        }
        #wrap:after{
            content: "";
            display: inline-block;
            height: 100%;
            width: 0px;
            vertical-align: middle;
        }
    </style>
</head>
<body>
<div id="wrap">
    <img src="images/1-middleRani.jpg">
</div>

未知元素的宽高的居中布局

定位+2D平移

div{
          border: 1px solid;
           /*left + top + 盒模型相关 = 300*/
              /*0 + 0 + auto + 0 + 1*2 + auto = 300*/
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
}

canvas中的垂直水平居中

canvas文本垂直水平居中

<body>
    <canvas width="300" height="300"></canvas>

    <script>
        var canvas = document.querySelector("canvas");
        canvas.style.background = "#ccc";
        var ctx = canvas.getContext("2d");

        ctx.font = "50px times";
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        ctx.fillText('hello',canvas.width/2,canvas.height/2);
    </script>

canvas图形垂直水平居中

<body>
    <canvas width="300" height="300"></canvas>
    <script>
        var canvas = document.querySelector("canvas");
        canvas.style.background = "#ccc";
        var ctx = canvas.getContext("2d");
        // ctx.fillRect(0,0,100,100);
        //图形居中
        ctx.fillRect(canvas.width/2-50,canvas.height/2-50,100,100);
    </script>
</body>
上一篇下一篇

猜你喜欢

热点阅读