HTML5/CSS3基础——div盒子水平垂直居中的三种方案
一、基于定位的使div盒子水平居中的三种方式1、使用top:50% left:50% 以及margin-top 和 margin-left 来进行定位2、使用top:50% left:50% 以及 transform: translate(-50%,-50%);3、使用top:0 left:0 right:0 bottom:0 以及 margin:auto 二、使用Flex 布局使div盒子水平居中三、使用js的方式使div盒子水平居中如何使盒子水平垂直居中,是我们在写页面布局经常能遇到的问题之一。以前我的我每次需要用到水平垂直居中的时候都会百度,每次百度总是又能找到不同的方式 而且还记不住:( 但今天就写系统的总结和整理了一下 我们使div盒子水平垂直居中的方式到底有哪些 跟我之前有着一样困惑的小伙伴一起来看吧~~
我们的html是这样滴:
<body><div class="box" id="box">水平垂直居中方案</div></body>
一、基于定位的使div盒子水平居中的三种方式
1、使用top:50% left:50% 以及margin-top 和 margin-left 来进行定位
注意:必须知道盒子的具体的宽和高,否则无法计算margin的值
.box{/* 盒子长为200,宽为100 背景为海蓝色*/height:100px;width:200px;background-color: aquamarine;position: absolute; /* 注意这是指盒子的左顶点在页面的中心 */top:50%;left:50%; margin-top:-50px; /* 盒子要向上移动自己高度的50% */margin-left:-100px;/* 盒子要向左移动自己宽度的50% */}html,body{position: relative;height:100%; margin:0;}
2、使用top:50% left:50% 以及 transform: translate(-50%,-50%);
来进行定位
注意:跟上一种相比,不需要宽和高,内容就会撑开盒子,但是兼容性差
.box{/* 盒子长为200,宽为100 背景为海蓝色*/height:100px;width:200px; background-color: aquamarine;position: absolute; top:50%;left:50%;/* 根据自有的宽度分别向上移和像左移动50% */transform: translate(-50%,-50%);}html,body{position: relative;height:100%; margin:0;}
3、使用top:0 left:0 right:0 bottom:0 以及 margin:auto
注意:盒子必须有宽和高,但不会用到宽和高进行具体的计算
.box{/* 盒子长为200,宽为100 背景为海蓝色*/height:100px;width:200px;background-color: aquamarine;position: absolute; top:0;left:0;right:0;bottom:0;margin:auto; }html,body{position: relative;height:100%; margin:0;}
二、使用Flex 布局使div盒子水平居中
.box{/* 盒子长为200,宽为100 背景为海蓝色*/height:100px;width:200px;background-color: aquamarine;}html,body{height:100%; margin:0;display: flex;/* 主轴位于中间 */justify-content:center ;/* 交叉轴位于中间 */align-items: center;}
三、使用js的方式使div盒子水平居中
水平居中方法: 将浏览器可视区的宽度(clientWidth) 减去 要居中元素本身的宽度(offsetWidth) /除以 2 +‘px’
垂直居中方法: 将浏览器可视区的高度(clientHeight) 减去 要居中元素本身的高度(offsetHeight) /除以 2 +‘px’
window.onload = function(){//var box =document.getElementById('box');let HTML =document.documentElement,winW=HTML.clientWidth,winH=HTML.clientHeight,boxW=box.offsetWidth,boxH=box.offsetHeight;box.style.position="absolute";box.style.left=(winW-boxW)/2+'px';box.style.top=(winH-boxH)/2+'px';}