各种情况的水平垂直居中

1.单行文本的水平垂直

  用height = line-height + text-align:center

2.内外宽高都知道的盒子可以用padding让上下相同,左右相同。css3中有calc()函数来算。

3.用margin来实现。水平方向上的可以直接margin-left:auto;margin-right:auto;来实现居中。垂直方向的用margin来实现有时候会出现margin重叠的情况。(在外层的元素上加一个overflow:hidden 这样就形成了一个新的bfc,这样的话两个元素就不处于同一个bfc中,所以不回发生margin重叠。)

4.外层relative 内层absolute ,top,left各50%,然后用margin负值来居中。(这个地方没有发生margin重叠是因为绝对定位元素已经脱离了正常的文档流。与外层元素不在一个流中。所以不相邻,所以不会产生margin折叠。浮动元素也是如此。而inline-block元素不会和其他元素发生边距重叠是因为margin重叠只发生在块级元素上面。然后这三个都会形成一个新的bfc,所以和其子元素也不会发生边距重叠。)

5.上面那种方法如果不知道宽高则可以用transform:translate(-50%,-50%);

6.relative偏移的百分比是通过父元素来定的。所以可以增加一个包裹的标签。

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style>
		.container {
			 100%;
			height: 200px;
			background-color: pink;
			position: relative;
		}
		.inner {
			 150px;
			height: 100px;
			background-color: transparent;
			position: absolute;
			left: 50%;
			top: 50%;
		}
		.in {
			position: relative;
			 100%;
			height: 100%;
			left: -50%;
			top: -50%;
			background-color: red;
		}
	</style>
</head>
<body>
<div class="container">
	<div class="inner">
		<div class="in">这个我是不知道宽高的</div>
	</div>
</div>
</body>
</html>

  7.inline-block元素也是可以用text-align:center来居中。

  8.一个绝对定位元素设置上下左右都为0.然后margin:auto 。auto。

w3c.org有说absolute性质的盒子,它的包含块的宽度等于它的盒模型的宽度 + left + right值,包含块的高度同理,盒模型包括margin-box、border-box、padding-box、content-box,而在这个居中方法中,.ele的left + right值是0,width是定值,width所在盒子包括了除了margin-box外的那三个box,margin都是auto值,按照上面那个公式,margin-left + margin-right的值应该等于包含块的宽度 - left的值 - right的值 - width的值,也就是说margin-left + margin-right的值等于除了width所占宽度外的剩下宽度,拥有剩下宽度后,就是平分其宽度,以让左右两边相等,达到居中。不过这样必须width left right都不为auto。然后mariginleftright为auto。

9. flex justify-content:center;align-items:center;

原文地址:https://www.cnblogs.com/zhuni/p/6379196.html