无论内容如何,我如何始终将容器水平和垂直对中?以下是我正在尝试做的基本示例。
这种方法是否正确,还是我的问题更容易解决?
<!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>
答案 0 :(得分:1)
.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
答案 1 :(得分:0)
正如Niels Keurentjes所说...... table-cell
很好fiddle
HTML:
<div class="outer">
<span class="inner">
<img src="http://www.google.co.in/trends/resources/2327917647-google-icon.png"/>
</span>
</div>
<div class="outer">
<span class="inner">
<span class="innerinner">blah blah blah blah blah blah blah blah blah blah</span>
</span>
</div>
的CSS:
.outer{
width:300px;
height:200px;
border:1px solid blue;
display:table;
text-align:center;
}
.inner{
display:table-cell;
vertical-align:middle;
border:1px solid red;
}
.inner img{
border:1px solid orange;
}
.innerinner{
border:1px solid red;
}