水平居中布局的三种经典方式

470 阅读3分钟

方法一:text-align&inline-block

在parent中设置text-align:center 在child中设置display:inlne-block

优缺点:

兼容性好,因为这两个属性都是css2中的内容,就是text-align具有继承性,有时会污染子元素css

三种display属性

  • block 块级元素

    • 父级元素的text-align属性对行内元素无效
  • inline 行内元素

    • 父级元素的text-align属性对行内元素有效
    • 该元素的width和height会变得无效,变成根据该元素的内容自动调整大小,如果没有内容就看不到这个元素
  • inline-block 行内块级元素

    • 拥有行内和块级元素的双重特点
    • 父级元素的text-align属性对行内元素有效和该元素的width和height会变得有效
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>水平居中</title>
		<style type="text/css">
			#parent{
				width: 100%;
				height: 200px;
				background: #ccc;
				text-align: center;
			}
			
			#child{
				width: 200px;
				height: 200px;
				background: #c9394a;
				display: inline-block;
			}
		</style>
	</head>
	<body>
		<div id="parent">
			<div id="child">
				水平居中
			</div>
		</div>
	</body>
</html>

text-align具有继承性,parent中child的内容也会水平居中,如果想要让child中的内容左对齐,可以对child添加text-align:left,覆盖属性。

方法二:table|block&margin

在child中设置display:table或block margin:0 auto

  • table是css的内容,相对设置block较兼容
  • div等block元素可以不用重复设置

优缺点

  • 只需要对child元素设置样式就可以实现效果
  • 如果child脱离文档流的话,会导致margin属性无效(child设置position: absolute|fixed;)

margin补课

margin属性代表外边距:

  • 一个值: 上下左右四个的边距
  • 两个值: 第一个表示上下边距 第二个表示左右边距
    • 0 auto 表示上下边距为0 左右=边距根据浏览器自动分配
  • 三个值:第一个表示上,第二个表示左右,第三个表示下
  • 四个值:上右下左
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>水平居中</title>
		<style type="text/css">
		#parent{
				width: 100%;
				height: 200px;
				background: #ccc;
			}
			
			#child{
				width: 200px;
				height: 200px;
				background: #c9394a;
				display: block;
				margin:0 auto;
			}
		</style>
	</head>
	<body>
		<div id="parent">
			<div id="child">
				水平居中
			</div>
		</div>
	</body>
</html>

方法三:absolute&left&transform

parent和child都加上position:absolute child设置left:50% child再向左平移自己宽度的一半 transfrom:translatex(-50%)

优缺点

parent是否脱离文档流,不影响子级元素的水平居中效果;但是transfrom属于css3中的属性,老浏览器不支持。

position补课:

  • static:默认不开启
  • absolute:绝对定位
    • 如果父级元素没有开启定位,这个绝对定位是以浏览器页面为定位的
    • 如果父级元素开启定位,这个绝对定位是相对父级元素为定位的
  • fixed:相对定位
  • relative:相对定位

transfrom补课:

transform 属性向元素应用 2D 或 3D 转换。该属性允许我们对元素进行旋转、缩放、移动或倾斜

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>水平居中</title>
		<style type="text/css">
			#parent{
				width: 100%;
				height: 200px;
				background: #ccc;
				position: absolute;
			}
			
			#child{
				width: 200px;
				height: 200px;
				background: #c9394a;
				position: absolute;
				left: 50%;
				transform: translateX(-50%)
			}
			
		</style>
	</head>
	<body>
		<div id="parent">
			<div id="child">
				水平居中
			</div>
		</div>
	</body>
</html>

大家来猜猜哪一种在企业开发中最常用:)