垂直水平居中的方式

来源:互联网 发布:中国经济网数据库 编辑:程序博客网 时间:2024/05/22 06:38

垂直水平居中的方式

垂直水平居中的方式列举出了四种方式:


方式一:利用属性拉扯的方式

<style type="text/css">    body,html{        background-color: #000000;    }    #box{        width: 400px;        height: 300px;        background-color: #FFFFFF;        position: absolute;        left: 0px;        right: 0px;        top: 0px;        bottom: 0px;        margin: auto;    }</style><body>    <div id="box"></div></body>

方式二:利用百分比

 #box{            width: 400px;            height: 300px;            background-color: #fff;            position: absolute;            left: 50%;            margin-left: -200px;            top: 50%;            margin-top: -150px;        }

方式三:利用伸缩盒子

<style type="text/css">        html,body{            height: 100%;        }        body{            display: flex;            justify-content: center;            align-items: center;        }        #box{            width: 400px;            height: 300px;            background-color: #ccc;        }    </style>

方式四:利用伪元素,可以理解为span

<style type="text/css">            html,body{                background-color: #000;                height: 100%;                text-align: center;/*水平居中*/            }            body:after{                content: '';                 height: 100%;                display: inline-block;                vertical-align: middle;             }            #box {               vertical-align: middle;/*垂直居中*/                 display: inline-block;               background-color: #fff;               width: 400px;               height: 300px;            }        </style>
原创粉丝点击