介绍5种常见的盒子在页面居中的方法

使用的CSS知识点: 定位; margin: auto; flex布局

能使盒子始终在浏览器窗口居中

不使用绝对定位实现居中

1.最简单的方式实现水平居中:margin: 0 auto;

原理 : 块级元素独占一行设置大小后水平方向会剩余空间,设置auto左右会自动分配剩余空间

  • 适用于body的子标签在页面居中; 盒子在其父盒子内居中

注意*盒子需要设置宽度才有效; 行内元素无效

<style>
    .box{
	width: 1200px; /*需要设置宽度才有效*/
	margin: 0 auto;
	}
</style>
<div class="box">盒子在页面居中</div>
<style>
    .box1{
        width: 400px;
        height: 200px;
        background: #aaaaff;
    }
    .boxChild {
        width: 100px;
        height: 100px;
        background: #55ff00;
        margin: 0 auto;
    }
</style>
<div class="box1">
	<div class="boxChild">盒子在父盒子中水平居中</div>
</div>

2.万能的flex布局实现水平垂直居中

.box1 {
	display: flex;
	justify-content: center;/*主轴对齐方式,水平居中*/
	align-items: center;/*垂直对齐方式,居中*/
	width: 400px;
	height: 200px;
	background: #aaaaff;
}
.boxChild {
	width: 100px;
	height: 50px;
	background: #ffaa7f;
}

需要用到绝对定位实现居中

<div class="box">盒子在页面居中</div>

已知盒子大小居中的方法有两种

若只需要在一个方向上居中,一般设置两个值就够了

3. 左偏移量left设为50%,再利用margin的负值让盒子水平左移动一半的宽度

/*只水平居中,如:*/
.box {
    width: 200px;
    height: 200px;
    position: absolute;
    left: 50%;
    margin-left: -100px; /*水平居中,让盒子水平左移动一半的宽度*/
   /* 同时设置即水平垂直居中
    *top:50%;
	*margin-top:-100px;
    */
}

4.通过绝对定位把上下左右值设为0 ,再用margin:auto实现居中

/*水平垂直居中:*/
.box {
    width: 200px;
    height: 200px;
    position: absolute;
    top: 0; 
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto; 
}

不知道盒子大小的情况下

5.使用位移transform:translate(-50%, -50%)

/*水平垂直居中*/
.box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

**😎今日份学习笔记分享结束**🎉🎉🎉

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐