未知宽高元素水平垂直居中

原文链接: https://www.mk2048.com/blog/blog.php?id=h0201jihkb1j&title=%E6%9C%AA%E7%9F%A5%E5%AE%BD%E9%AB%98%E5%85%83%E7%B4%A0%E6%B0%B4%E5%B9%B3%E5%9E%82%E7%9B%B4%E5%B1%85%E4%B8%AD

未知宽高元素水平垂直居中

一、vertical-align:middle

<style>
*{
	margin: 0px; 
	padding: 0px;
}
.wrap {
	position: absolute;
	width: 100%; 
	height: 100%; 
	text-align: center; 
	background: #92b922;
}
.test {
	background: #de3168; 
	display: inline-block; 
	color: #fff; 
	padding: 20px;
}
.vamb {
	display: inline-block;
	width: 0px; 
 	height: 100%; 
	vertical-align: middle;
}
</style>
<div class="wrap">
	<b class="vamb"></b>
	<div class="test">
		水平垂直居中了吧<br>
		两行文字哦
	</div>
</div>

二、transform

<style>
*{
	margin:0px; 
	padding:0px;
}
body{
	background: #92b922;
}
.test {
	background: #de3168; 
	color: #fff;
	position: absolute; 
	left:50%; 
	top:50%; 
	-webkit-transform:translate(-50%,-50%); 
	transform:translate(-50%,-50%);
}
</style>

三、利用弹性盒模型

<style>
*{
	margin: 0px; 
	padding: 0px;
}
.flex {
	display:-webkit-box; 
	display:-ms-flex; 
	display:-webkit-flex; 
	display:flex;
}
.flex-hc {
	-webkit-box-pack:center; 
	-ms-justify-content:center; 
	-webkit-justify-content:center; 
	justify-content:center;
}
.flex-vc {
	-webkit-box-align:center; 
	-ms-align-items:center; 
	-webkit-align-items:center; 
	align-items:center;
}
.wrap {
	position:absolute; 
	width:100%; 
	height:100%; 
	left:0px; 
	top:0px; 
	background: #92b922;
}
.test {
	background: #de3168; 
	color: #fff;
}
</style>
<div class="wrap flex flex-hc flex-vc">
	<div class="test">
		水平垂直居中了吧<br>
		两行文字哦
	</div>
</div>

四、表格

<style>
*{
	margin: 0px; 
	padding: 0px;
}
.wrap {
	width: 600px; 
	height: 600px; 
	display: table-cell; 
	vertical-align: middle; 
	text-align: center; 
	background: #92b922;
}
.test {
	background: #de3168; 
	display: inline-block; 
	color: #fff; 
	padding: 20px;
}
</style>
<div class="wrap">
	<div class="test">
		水平垂直居中了吧<br>
		两行文字哦
	</div>
</div>

更多专业前端知识,请上 【猿2048】www.mk2048.com

猜你喜欢

转载自blog.csdn.net/qq_29069777/article/details/102756281