页面架构(笔记2)——垂直居中布局

需求要求:

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

2,子容器与父容器的自身高度都是自适应的

image image image

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

<style type="text/css">
    body{margin:20px;}
    .parent{width:4em;height:500px;}
    .child{width:100%;}
    
    .parent{
        display: table-cell;
        vertical-align: middle;
    }
</style>
<body>
<div class="parent">
    <div class="child">DEMO</div>
</div>
</body>
要点:
vertical-align属性可以作用在inline元素,inline-block元素以及table-ceil上
方案一优点:兼容性好,兼容Ie8+(包括ie8)
缺点:.Ie6.7不兼容table-ceil,可以通过改成table结构的方法来兼容

解决方案二(absolute+transform)

<style type="text/css">
    body{margin:20px;}
    .parent{width:4em;height:500px;}
    .child{width:100%;}

    .parent{
        position: relative;
    }
    .child{
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }
</style>
<body>
<div class="parent">
    <div class="child">DEMO</div>
</div>
</body>
方案二优点:absolute脱离文档流,不会对其他元素产生影响,
缺点:transform:不支持Ie6,7,8,兼容性达不到要求,可以在不同的浏览器前加上私有前缀

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

<style type="text/css">
    body{margin:20px;}
    .parent{width:4em;height:500px;}
    .child{width:100%;}

    .parent{
        display: flex;
        align-items: center;
    }
</style>
<body>
<div class="parent">
    <div class="child">DEMO</div>
</div>
</body>
方案一优点:只要给parent设置就可以了
缺点:flex不支持Ie6,7,8,兼容性达不到要求
原文地址:https://www.cnblogs.com/zz334396884/p/5199392.html