让一个盒子实现水平垂直居中

156 阅读1分钟

@[toc]

一、盒子居中的三种定位

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			body{
				height:100%
				overflow:hidden	
				/* position:relative */
			}
			#box{
				width:200px;
				height: 200px;
				background-color: antiquewhite;
				text-align: center;
				line-height: 200px;
			}
			/* 绝对定位法1 */
			/* #box{
				position: absolute;
				top:0px;
				bottom: 0px;
				right:0px;
				left:0px;
				margin: auto;
			} */
			/* 绝对定位法2 */
			/* #box{
				position: absolute;
				top:50%;
				left:50%;
				margin-left: -100px;
				margin-top: -100px;
				/* 负值大小为盒子宽度,高度一半*/
			} */
			/* 绝对定位法3 */
			 #box{
				position: absolute;
				top:50%;
				left:50%;
				transform: translate(-50%,-50%);
			}
			
		</style>
	</head>
	<body>
		<div id="box">
			盒子居中
		</div>
	</body>
</html>

效果展示: 在这里插入图片描述

二、盒子居中-flex布局

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .box {
            width: 467px;
            height: 377px;
            border: 1px solid red;
            margin: 150px auto;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .one {
            width: 177px;
            height: 177px;
            background-color: red;
        }
    </style>
</head>

<body>

    <div class="box">
        <div class="one"></div>
    </div>
</body>

</html>


效果展示: 在这里插入图片描述

三、盒子居中——js代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			html,
			body{
				height: 100%;
				overflow: hidden;
				position: relative;
			}
			.box{
				/* position: absolute; */
				width: 200px;
				height: 200px;
				background-color: antiquewhite;
				line-height: 200px;
				text-align: center;
			}
		</style>
	</head>
	<body>
		<div class="box" id="box">
			hezijuzhong
		</div>
		<script type="text/javascript">
			//document.documentElement获取html;document.body获取body
			//clientWidth,clientHeight获取对象的宽度和高度
			// clientWidth = width+左右padding
			// clientHeigh = height + 上下padding 
			// offsetWidth = width + 左右padding + 左右boder
			// offsetHeith = height + 上下padding + 上下boder
			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'
			// box.style.background = "#000"黑
			//box.style.background = "red"
			//box.style.background = "#fff"白
		</script>
	</body>
</html>

效果展示: 在这里插入图片描述