CSS实现div盒子水平垂直居中的方式

网上看到有很多方式,这里记录一下我用起来顺手的几种方式,这里敲黑板做笔记,哈哈~~

<div id='container'>
    <div class='middle'>
    </div>
</div>

首先预备工作,假设这是登录界面,那通常会涉及到背景图片撑满屏幕

 <style>
        html,body{
            height:100%;
        }
        #container{
			width:100%;
			height:100%;
			position:fixed;
			top:0;
            left:0;
            background-color: aqua; //这里用背景色充当背景图片
		}
 </style>

明显看到会出现滚动条;可以用两种方式让滚动条消失:

html,body{
    height:100%;
    /* overflow: hidden; */  //方式一
    margin:0;
    padding: 0;
}

好啦下面,开始进入正题,实现 class=‘middle’ 这个div盒子的垂直居中显示

1.前提是设置好div盒子的高度和宽度

 .middle{
		width:100px;
    	height:100px; 
        background-color:tomato;
         /* 水平居中 */
        margin: 0 auto;
  }

(1) position:absolute

方式一:元素自身已知宽度

.middle{
       width:100px;
       height:100px; 
       background-color:tomato;
        /* 水平垂直居中*/
       position: absolute;
       top:50%;
       left:50%; 
       margin: -50px 0 0 -50px;
 }

方式二:元素自身未知宽度

.middle{
    width:100px;
    height:100px; 
    background-color:tomato;
     /* 水平垂直居中*/
    position: absolute;
    top:50%;
    left:50%; 
    transform: translate(-50%,-50%);
}

方式三:

.middle{
     width:100px;
     height:100px; 
     background-color:tomato;
     /* 水平垂直居中*/
     position: absolute; 
     top:0;
     left:0;
     right:0;
     bottom:0;
     margin:auto;
}

(2)display:flex

方式一:

#container{
    width:100%;
    height: 100%;
    /* 子元素middle垂直居中 */
    display: flex;
    justify-content: center; // 水平居中
    align-items:center;	// 垂直居中
}

方式二:

#container{
     width:100%;
     height: 100%;
  	 display: flex;
}
.middle{
     width:100px;
     height:100px; 
     background-color:tomato;
     margin:auto;
}

(3)display:table;display:table-cell;display:inline-block;

 <div id='container'>
        <div class='middle'>
            <div class='inner'></div>
        </div>
</div>
#container{
       width:100%;
       height: 100%;
       display: table;
}
.middle{
	   width:100px;
	   height:100px; 
	   background-color:tomato;
	   /* 这边会发现 middle 的背景色会铺满整个屏幕 */
	   display:table-cell;
	   vertical-align: middle;
	   text-align: center; 
}
.inner{
    width:50px;
    height:50px;
    background-color: yellow;
    /* 实现水平垂直居中*/
    display: inline-block;
}

OK~~~方法还有很多种,以上是我熟悉的,后面碰到别的情况再做记录。

猜你喜欢

转载自blog.csdn.net/Zhou07182423/article/details/85678817