用于垂直居中的CSS3方法

时间:2017-02-07 14:50:17

标签: javascript css3

目前我找到了两种不同的垂直居中方法。



footer {
	height: 10em;
	position: absolute; left: 0; right: 0;
	color: white; background-color: #333;
}
footer > p {
	background-color: lightBlue; 
}


footer.vcenter1 { bottom: 11em; transform-style: preserve-3d; }
footer.vcenter2 { bottom: 0; }

.vcenter1 > p {
	margin: 0;
	position: absolute;
	top: 50%; transform: translateY(-50%);
}

.vcenter2 { white-space: nowrap;  word-spacing:-.25em; }
.vcenter2:before, .vcenter2 > p { display: inline-block; vertical-align: middle; }
.vcenter2:before { content:"";  height: 100%; }
.vcenter2 > p { white-space: normal; word-spacing: normal; }

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<title>Test</title>
	<link href="Test.css" rel="stylesheet" />
</head>
<body>

<footer class="vcenter1">
	<p>
		test text
		some text   more text   and more text...   and more text...  and more text... and more text... and more text... and more text... and more text...
		<br>line3
	</p>
</footer>
<footer class="vcenter2">
	<p>
		test text
		some text   more text   and more text...   and more text...  and more text... and more text... and more text... and more text... and more text...
		<br>line3
	</p>
</footer>

</body>
</html>
&#13;
&#13;
&#13;

在Firefox和Internet Explorer中,两者似乎表现完全相同。但是,这两种方法中的任何一种都可能导致其他浏览器出现问题吗?

显然vcenter1方法(transform:translateY)是较少的CSS代码,但我从来没有习惯于在运行时为静态定位移动对象的本质。

1 个答案:

答案 0 :(得分:0)

据我所知,vcenter1(使用位置和变换居中)在所有现代浏览器中都能完美运行see browser support

您也可以使用flexbox see browser support

&#13;
&#13;
footer {
	height: 10em;
	position: absolute; left: 0; right: 0;
	color: white; background-color: #333;
}
footer > p {
	background-color: lightBlue; 
}

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

.vcenter4 {
    height: 10em;
    line-height: 10em;
    text-align: center;
}
.vcenter4 > p {
    background-color: lightBlue;
    vertical-align: middle;
    display: inline-block;
    line-height: normal;
}
&#13;
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<title>Test</title>
	<link href="Test.css" rel="stylesheet" />
</head>
<body>

<div class="vcenter4">
	<p>
		test text
		some text   more text   and more text...   and more text...  and more text... and more text... and more text... and more text... and more text...
		<br>line3
	</p>
</div>

<footer class="vcenter3">
	<p>
		test text
		some text   more text   and more text...   and more text...  and more text... and more text... and more text... and more text... and more text...
		<br>line3
	</p>
</footer>

</body>
</html>
&#13;
&#13;
&#13;