首页 > Web开发 > 详细

css实现水平垂直居中

时间:2019-03-31 10:02:36      阅读:128      评论:0      收藏:0      [点我收藏+]

1、基于flex布局

.box{
            width: 300px;
            height: 300px;
            background-color: #0000ff;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .main{
            width: 100px;
            height: 100px;
            background-color: #0e5370;
        }
/*****或*****/
 .box{
             width: 300px;
             height: 300px;
             background-color: #0000ff;
             display: flex;
         }
        .main{
            width: 100px;
            height: 100px;
            background-color: #0e5370;
            margin: auto;
        }

2、基于绝对定位

/********** 父元素设置为:position: relative;
            子元素设置为:position: absolute;
            距上50%,据左50%,然后减去元素自身宽度的距离就可以实现
        ********************/
        .box{
            width: 300px;
            height: 300px;
            background-color: #0000ff;
            position: relative;
        }
        .main{
            width: 100px;
            height: 100px;
            background-color: #0e5370;
            position: absolute;
            top: 50%;
            left: 50%;
            margin: -50px 0 0 -50px;
        }
        /*position transform 元素未知宽度
        如果元素未知宽度,只需将上面例子中的margin: -50px 0 0 -50px;替换为:transform: translate(-50%,-50%);*/
        .box{
            width: 300px;
            height: 300px;
            background-color: #0000ff;
            position: relative;
        }
        .main{
            width: 100px;
            height: 100px;
            background-color: #0e5370;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }

3、基于表格样式

/******* table-cell布局
        因为table-cell相当与表格的td,td为行内元素,无法设置宽和高,所以嵌套一层,嵌套一层必须设置display: inline-block;
        ******/
        .box{
            width: 300px;
            height: 300px;
            background-color: #0000ff;
            display: table;
        }
        .main{
            display: table-cell;
            text-align: center;
            vertical-align: middle;
        }
        .inner{
            width: 100px;
            height: 100px;
            background-color: #0e5370;
            display: inline-block;
        }
<div class="box">
    <div class="main">
        <div class="inner"></div>
    </div>
</div>

 

css实现水平垂直居中

原文:https://www.cnblogs.com/wenzizaigaoge/p/10537020.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!