无论内容如何,如何始终使容器水平和垂直居中?下面是我正在尝试做的一个基本示例。
这个方法是否正确,或者是否有更简单的解决方案来解决我的问题?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>3 columns</title>
<style>
div.container {
height: 200px;
width: 100%;
margin-left: auto;
margin-right: auto;
margin-top: 25%;
margin-bottom: 20%;
}
div.col {
float: left;
width: 25%;
}
</style>
</head>
<body>
<div class="container">
<div class="col" align="center">This is col 1</div>
<div class="col" align="center">This is col 2</div>
<div class="col" align="center">This is col3</div>
</div>
</body>
</html>
最佳答案
.container {
position: absolute;
left: 50%;
top: 50%;
/*
Nope =(
margin-left: -25%;
margin-top: -25%;
*/
/*
Yep!
*/
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
/*
Not even necessary really.
e.g. Height could be left out!
*/
width: 40%;
height: 50%;
}
来源:http://css-tricks.com/centering-percentage-widthheight-elements/
请注意,在撰写本文时,transform
属性需要某些浏览器的前缀(-ms
、-webkit
)。 http://caniuse.com/transforms2d
关于html - 无论内容如何,如何始终将容器水平和垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19261139/