1. 程式人生 > 實用技巧 >css 盒居中五大方案

css 盒居中五大方案

盒子水平居中五大方案

  • 定位:3種
  • display:flex
  • JS-dom
  • 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;    //盒子必須轉換為文字格式
}