css实现居中的几种方法

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>css实现居中的几种方法</title>
</head>
<body>
<div class="parent">
    <div class="child"></div>
</div>
<style>
    .parent{
        width: 200px;
        height: 200px;
        background: #ccc;
        position: relative;

        /*1、flex布局实现。水平居中justify-content,垂直居中align-items*/
        display:flex;
        justify-content: center;
        align-items: center;
    }

    .child{
        width: 50px;
        height: 50px;
        background: #aaa;
        position: absolute;

        /*2、margin:auto实现。全居中:auto、水平居中:0 auto、垂直居中:auto 0*/
        /*left:0;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;*/

        /*3、Transforms变形实现。left和top值为父级百分比,translate值为自己百分比*/
        /*left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);*/

        /*4、margin负间距实现。margin负值为宽高的-1/2*/
        /*left: 50%;
        top: 50%;
        margin-left: -25px;
        margin-top: -25px;*/
    }
</style>
</body>
</html>

  

猜你喜欢

转载自www.cnblogs.com/huangtonghui/p/8933602.html