第一种方法

<style>
	html,body{
		height:100%;
	}
	body{
		position:relative;
		margin:0;
	}
	.container{
		position:absolute;
		top:50%;
		height:50%;
		transform:translate(-50%,-50%);
	}
</style>

<body>
	<div class="container">正中心的盒子</div>
</body>

说明:

  1. 设置父元素为relative,子元素为absolute可以使子元素相对于父元素进行绝对定位。
  2. 设置left和top,各是页面的50%的大小
  3. 然后使用transfrom:translate(-50%,-50%);使元素自身在水平和竖直方向,向左和向上偏移自身的50%,从而达到使容器在页面的正中心的目的。
  4. 给html和body(即父元素)添加height属性是必要的。

第二种方法

<style>
    html,body{
        height: 100%;
        margin: 0;
    }
    .container{
        display: flex;
        justify-content: center;
        align-items: center;
        /*以上三行是关键代码*/
        width: 100%;
        height: 100%;
        background-color: antiquewhite;
    }
    .box{
        width: 300px;
        height: 300px;
        background-color: aqua;
    }
</style>
<body>
    <div class="container">
        <div class="box">我是正中心的盒子</div>
    </div>
</body>

说明:

  1. 设置html和body的高度占满浏览器(必要),去除掉外边距(非必要)
  2. 设置以下属性
.container{
	display:flex;/*弹性盒子布局*/
	justify-content:center;/*水平排列方式设定*/
	align-items:center;/*垂直排列方式设定*/
}
Logo

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

更多推荐