css水平垂直居中的几种方法

2019-03-06 21:06:50  阅读 3846 次 评论 0 条

方法一:div绝对定位水平垂直居中【margin 负间距】,这种目前使用的比较多,限制是需要定义div的宽度和高度,并且内容可能会超出容器,代码如下:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>水平垂直居中方法</title>
        <style type="text/css">
            .sys-no1{
                width:200px;
                height:200px;                
                left:50%;
                top:50%;
                position: absolute;
                margin-left:-100px;
                margin-top:-100px;
                background:blue;
            } 
        </style>
    </head>
    <body>
        <div class="sys-no1"></div>
    </body>
</html>



方法二:div绝对定位水平垂直居中【margin:auto实现绝对定位元素的居中】,这种方法限制是IE7及以前版本不支持,代码如下:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>水平垂直居中方法</title>
        <style type="text/css">
            .sys-no2{
                width: 200px;
                height: 200px;
                position:absolute;
                left:0;
                top: 0;
                bottom: 0;
                right: 0;
                margin: auto;
                background: blue;
            } 
        </style>
    </head>
    <body>
        <div class="sys-no2"></div>
    </body>
</html>



方法三:transform法,这种方法IE8及以前版本不支持,代码如下:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>水平垂直居中方法</title>
        <style type="text/css">
            .sys-no3{
                width: 50%;
                height: 20%;
                position: absolute;
                top:50%;/* 定位父级的50% */
                left: 50%;
                transform:translate(-50%, -50%);/*自己的50% */
                -webkit-transform:translate(-50%, -50%);
                -ms-transform:translate(-50%, -50%);
                background: blue;
            }
        </style>
    </head>
    <body>
        <div class="sys-no3"></div>
    </body>
</html>



方法四:flex布局法

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>水平垂直居中方法</title>
        <style type="text/css">
            .box{
                width: 100%; 
                height: 100%; 
                margin: auto; 
                display: flex; 
                align-items: center; // 垂直居中
                justify-content: center;// 水平居中
            }
            .innerbox{
                width:200px;//可以省略
                background:blue;
            }
        </style>
    </head>
    <body>
<div class="box">
    <div class="innerbox">垂直水平居中</div>
</div>
    </body>
</html>



微信扫码查看本文
本文地址:https://www.yangguangdream.com/?id=2030
版权声明:本文为原创文章,版权归 编辑君 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?