css控制元素 水平垂直居中

控制元素居中核心代码为 

position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;

 

css:

     /* 容器 */
        .wrap {
            position: relative;
            height: 600px;
            width: 500px;
            border: 1px solid #ccc;
            margin: 0 auto;
        }
        /* 需要居中的元素 */
        .box {
            width: 200px;
            height: 200px;
            border: 1px solid #ccc;
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            text-align: center;
            line-height: 200px;
        }

html:

<div class="wrap">
        <div class="box">
            我是居中的元素
        </div>
</div>

效果如下:

注:如果需要元素相对于整个页面居中可使用 固定定位 position: fixed; 或者其所有父级元素均不使用定位。

posted @ 2019-03-30 17:12  那时年少青衫薄。  阅读(140)  评论(0编辑  收藏  举报