css 盒居中五大方案

盒子水平居中五大方案

  • 定位:3种
  • display:flex
  • JS-dom
  • position 定位
  • display:table-cell(扩展)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>		
			*{
				margin: 0;padding: 0;	
			}
			body{
				height: 100%;
				overflow: hidden;
			}
			.box{
				width: 100px;
				height: 100px;
				background-color: aquamarine;
				text-align: center;
				line-height: 100px;
			}
			
			/* .box{
				//盒子必须有宽高,且需要计算宽高
				position: absolute;
				top:50%;
				left:50%;
				margin-top: -50px;
				margin-left: -50px; 
			} */
			/* .box{
				/* 盒子必须有宽高,但不需要计算宽高 */
				position: absolute;
				top:0;
				left:0;
				bottom: 0; 
				right: 0;
				margin: auto;
			} */
			/* .box{
				/* 盒子可以没宽高,但需要考虑兼容 */
				position: absolute;
				top:50%;
				left:50%;
				transform: translate(-50%,-50%);
			} */
		</style>
	</head>
	<body>
		<div class="box">我是C位</div>
	</body>
</html>

display:flex
JavaScript

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>		
			*{
				margin: 0;padding: 0;	
			}
			html,
			body{
				/* position: relative; */
				height: 100%;
				overflow: hidden;
			}
			/* body{				
				display: flex;
				justify-content: center;
				align-items: center;
			}	 */		
			.box{
				width: 100px;
				height: 100px;
				background-color: aquamarine;
				text-align: center;
				line-height: 100px;
			}			
		</style>
	</head>
	<body>
		<div class="box" id="box">我是C位</div>
		<script>
			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";
		</script>
	</body>
</html>

display:table-cell

.father{
	width:xxx;
    height:xxx;			
	display: table-cell;
	vertical-align: middle;
	text-align: center;
        //宽高不能是百分比
}
.son{
    display:inline-block;    //盒子必须转换为文本格式
}
posted @ 2020-08-01 18:56  Daeeman  阅读(221)  评论(0)    收藏  举报