0
点赞
收藏
分享

微信扫一扫

常见的CSS居中布局

窗外路过了谁 2022-03-12 阅读 77
csscss3

flex布局

.box {
    width: 500px;                
    height: 500px;               
    border: 1px solid red;      
    margin: 100px auto;          
    display: flex;              /* 核心代码 */
    justify-content: center;    /* 核心代码 */
    align-items: center;        /* 核心代码 */
}
.children {
    width: 100px;
    height: 100px;
    background-color: #ccc;
}

position定位

// 第一种写法,用于不知道子元素的宽高
.box {
    width: 500px;                
    height: 500px;               
    border: 1px solid red;      
    margin: 100px auto;     
    position: relative;    /* 核心代码 */  
}
.children {
    width: 100px;
    height: 100px;
    background-color: #ccc;
    position: absolute;                 /* 核心代码 */
    top: 50%;                           /* 核心代码 */
    left: 50%;                          /* 核心代码 */
    transform: translate(-50%,-50%);    /* 核心代码 */
}


// 第二种写法,用于知道子元素的宽高
.box {
    width: 500px;                
    height: 500px;               
    border: 1px solid red;      
    margin: 100px auto;     
    position: relative;    /* 核心代码 */  
}
.children {
    width: 100px;
    height: 100px;
    background-color: #ccc;
    position: absolute;         /* 核心代码 */
    top: 50%;                   /* 核心代码 */
    left: 50%;                  /* 核心代码 */
    margin-left: -50px;         /* 核心代码 */
    margin-top: -50px;          /* 核心代码 */
}

// 第三种写法,用于不知道子元素的宽高
.box {
    width: 500px;                
    height: 500px;               
    border: 1px solid red;      
    margin: 100px auto;     
    position: relative;             /* 核心代码 */
}
.children {
    width: 100px;
    height: 100px;
    background-color: #ccc;
    position: absolute;             /* 核心代码 */
    top: 0;                         /* 核心代码 */
    left: 0;                        /* 核心代码 */
    right: 0;                       /* 核心代码 */
    bottom: 0;                      /* 核心代码 */
    margin: auto;                   /* 核心代码 */
}

table-cell

.box {
    width: 500px;                
    height: 500px;               
    border: 1px solid red;      
    margin: 100px auto;     
    display: table-cell;            /* 核心代码 */
    vertical-align: middle;         /* 核心代码 */
}
.children {
    width: 100px;
    height: 100px;
    background-color: #ccc;
    margin: 0 auto;                 /* 核心代码 */
}

其他

以上的是常用的好用的,但是呢,定位不止以上几种,还有网格grid布局,还有上面方法的变种等等,都无所谓,像网格布局不推荐了,就不写了,非要写这个,请自行用百度Google一下。

举报

相关推荐

0 条评论