页面架构(笔记3)——水平垂直都居中布局

需求要求:

1.子容器相对父容器水平居中、垂直居中

2,子容器与父容器的自身高度宽度都是未知的

image image image image

解决方案一(inline-block+text-align+table-cell+vertical-align)

<style type="text/css">
    body{margin:20px;}
    .parent{width:200px;height:300px;}
    
    .parent{
        text-align: center;
        display: table-cell;
        vertical-align: middle;
    }
    .child{
        display: inline-block;
    }
</style>
<body>
<div class="parent">
    <div class="child">DEMO</div>
</div>
</body>

解决方案二(absolute+transform)

<style type="text/css">
    body{margin:20px;}
    .parent{width:200px;height:300px;}
    
    .parent{
        position: relative;
    }
    .child{
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }
</style>


<body>
<div class="parent">
    <div class="child">DEMO</div>
</div>
</body>

解决方案三(flex+justify-content+align-items)

<style type="text/css">
    body{margin:20px;}
    .parent{width:200px;height:300px;}
    
    .parent{
        display: flex;
        justify-content: center;
        align-items: center;
    }
</style>

<body>
<div class="parent">
    <div class="child">DEMO</div>
</div>
</body>
原文地址:https://www.cnblogs.com/zz334396884/p/5199422.html