ITPub博客

首页 > IT职业 > IT图书 > 总结:css保持浮层水平垂直居中的几种方法

总结:css保持浮层水平垂直居中的几种方法

IT图书 作者:libinbin 时间:2021-09-09 09:01:27 0 删除 编辑

1.利用flexbox布局

        .parent{
            width: 100%;
            height: 37.5rem/* 600px */;
            background: #09c;
            display: flex;
            justify-content:center;     /* 水平居中 */
            align-items:center;         /* 垂直居中 */
            /* flex-direction:column; */    /* 一列显示 */
        }
        .children{
            width: 100px;
            height: 100px;
            background-color: #eee;
            border: 1px dashed #000;
            margin: 5px;
            /*如果children下面还有子元素的话,可以嵌套使用*/
            /* display: flex;
            justify-content: center;
            align-items:center;  */
        }

2.利用绝对定位与transform

        .parent{
            position: absolute;
            background-color: #eee;
            width: 100%;
            height: 100%;
        }
        .parent .children{
            background-color: #751;
            width: 200px;
            height: 200px;
            position: absolute;
            top: 50%;
            left: 50%;
            -webkit-transform: translate(-50%,-50%);
        }

3.将父元素定位,子元素绝对定位,利用margin负值为子元素宽高的一半来实现。

        .parent{
            position: relative;
            background-color: #eee;
            height: 600px;
            width: 100%;
        }
        .parent .children{
            background-color: #751;
            width: 200px;
            height: 200px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin: -100px 0 0 -100px;
        }

4.利用定位与margin:auto

        .parent{
            width: 100%;
            height: 37.5rem/* 600px */;
            background: #09c;
            position: relative;
        }
        .children{
            width: 100px;
            height: 100px;
            background-color: #eee;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
        }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/359/viewspace-2798701/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2020-07-23

  • 博文量
    0
  • 访问量
    944