CSS3 Flex實現元素的水平居中和垂直居中

一.水平居中

1.單個元素水平居中

.box {
	display: flex;
	justify-content: center;   /*水平居中*/
}

2.多個h1元素水平居中

<!--html代碼-->

<div class="box">
	<h1>flex彈性佈局justify-content屬性實現元素水平居中</h1>
	<h1>flex彈性佈局justify-content屬性實現元素水平居中</h1>
	<h1>flex彈性佈局justify-content屬性實現元素水平居中</h1>
</div>

csscss

.box {
	display: flex;
	justify-content: center;
	width: 100%;
	background: #0099cc
}

h1 {
	font-size: 1rem;
	padding: 1rem;
	border: 1px dashed #FFF;
	color: #FFF;
	font-weight: normal;
}

效果圖html

 

二.垂直居中

1.單個h1標籤垂直居中佈局

.box {
	display: flex;
	align-items:center;   /*垂直居中*/
}

2.多個h1標籤並排垂直居中flex

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

<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<style>
	.box {
		display: flex;
		width: 980px;
		height: 30rem;
		align-items: center;
		background: #6161d1
	}

	h1 {
		font-size: 1rem;
		padding: 1rem;
		border: 1px dashed#FFF;
		color: #FFF
	}

</style>

<body>
	<div class="box">
		<h1>flex彈性佈局justify-content屬性實現元素垂直居中</h1>
		<h1>flex彈性佈局justify-content屬性實現元素垂直居中</h1>
		<h1>flex彈性佈局justify-content屬性實現元素垂直居中</h1>
	</div>
</body>

 

 

 

總結:spa

經常使用代碼:code

display: flex;
align-items: center;      /*垂直居中*/
justify-content:center;   /*水平居中*/
相關文章
相關標籤/搜索