您好,欢迎来到测品娱乐。
搜索
您的当前位置:首页Css实现垂直水平居中的六种方法_html/css_WEB-ITnose

Css实现垂直水平居中的六种方法_html/css_WEB-ITnose

来源:测品娱乐


经常在项目中用到,今天总结了一下:

演示地址:http://codepen.io/anon/pen/xGdpOa

以下两个类为公共类,便于更好的显示效果,非核心代码

	.common{	width: 600px;height: 180px;	background-color:#56abe4;	color: #fff;	margin: 15px auto; 	border-radius: 3px;	 }	.con{	display: inline-block;	padding: 15px;	width: 160px;	height: 80px;	background-color: orange;	}

  

正文部分:

第一种方法:

/*position: absolute;top:0;right: 0;bottom: 0;left: 0;margin: auto;*/

HTML结构:

	position: absolute;	top:0;right: 0;bottom: 0;left: 0;	margin: auto;	

CSS部分:

	.block1{	position: relative;	}	.inner1{	position: absolute;	top:0;right: 0;bottom: 0;left: 0;	margin: auto;	}

 

第二种方法: 

/*display: table-cell*/

HTML结构:

 	display: table-cell;	text-align: center;	vertical-align: middle;	

CSS部分: 

.block2{	display: table-cell;	text-align: center;	vertical-align: middle;	}

  

第三种方法:

/*display: flex;*/

HTML结构:

	 display: flex; align-items: center; justify-content: center;	

CSS部分:

	.block3{	display: flex;	align-items: center;	justify-content: center;	}

  

 第四种方法:

/*负定位*/

HTML结构:

	 position: absolute;	top: 50%;	left: 50%; 并利用负定位消除元素的上下,左右偏移	

CSS部分:

	.block4{ position: relative;	}	.inner4{	position: absolute;	top: 50%;	left: 50%;	margin-top: -55px;/*80/2+15=55*/ margin-left: -95px;/*160/2+15=95*/	}

  

 第五种方法:

/*transform*/

HTML结构:

	position: absolute;	top: 50%;	left: 50%; transform:translate(-50%,-50%);	

CSS部分:

	.block5{ position: relative;	}	.inner5{	position: absolute;	top: 50%;	left: 50%; transform:translate(-50%,-50%); word-wrap: break-word;	}

  

第六种方法:(兼容性较好)

/*行内块*/

HTML结构:

	行内块:
谨记span标签与该div之间是没有空白的,否则会产生误差

CSS部分:

	.block6{ text-align:center;}	.inner6,.block6 span{	 display:inline-block;	 *display:inline;	 zoom:1; 	 vertical-align:middle;	}	.inner6{max-width:100%;max-height:100%;}	.block6 span{width:0;height:100%;}

以上几种方案存在兼容性问题,在使用时请先查询核心css的浏览器兼容情况,查询地址:http://caniuse.com/

以上。

欢迎补充~

Copyright © 2019- cepb.cn 版权所有 湘ICP备2022005869号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务