我想垂直对齐一个div(rectangle
),这个div没有任何父母,我创建了一个(container
)来使用vertical-align
属性但我可以如果有人知道更好的方法,请删除它。
我只想将一个矩形居中放入body
div(水平和垂直)并使其响应。
这是我尝试但它不起作用(矩形保持靠近窗口顶部):
<html>
<head>
<style>
.rectangle {
width: 88%;
height: 87%;
margin: auto;
padding:10px;
background:red;
display:inline-block;
vertical-align:middle;
}
.container {
text-align: center;
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div class="rectangle">
</div>
</div>
</body>
</html>
是否可以仅使用CSS实现,还是需要javascript?
答案 0 :(得分:2)
有几种方法可以解决这个问题。由于您已将其标记为CSS3,因此我们可以使用一些较新的方法来实现此目的。此外,克里斯科耶已经做了一些关于CSS垂直居中的好文章。一些链接是:
http://css-tricks.com/centering-in-the-unknown/
http://css-tricks.com/centering-percentage-widthheight-elements/
如果你知道你想要居中的元素的高度,你可以绝对定位它,并考虑它的宽度/高度和负边距。
另一种方法是设置元素和主体以使用css显示表。
另一个新兴的选择是flexbox规范,它为你处理了很多繁重的工作。有关flexbox的更多信息,请访问:
http://css-tricks.com/using-flexbox/ http://css-tricks.com/snippets/css/a-guide-to-flexbox/
以及如何将flexbox与其他样式混合的示例:
http://css-tricks.com/replicating-google-hangouts-chat/
我个人最喜欢翻译选项,但随着flexbox支持的增长,这种类型的布局最容易这样。
答案 1 :(得分:0)
<html>
<head>
<style>
.rectangle {
background: #000;
height: 200px;
width: 200px;
}
.container {
width: 100%; /* Firefox needs this */
height: 100%; /* Height can be anything */
/* WebKit (Chrome & Safari) */
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
/* Firefox */
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
/* IE */
display: -ms-box;
-ms-box-pack: center;
-ms-box-align: center;
/* Native CSS */
display: box;
box-pack: center;
box-align: center;
background: red;
}
</style>
</head>
<body>
<div class="container">
<div class="rectangle">
</div>
</div>
</body>
</html>
Internet Explorer 10支持替代的-ms-flex-align属性。 Firefox支持另一种方法-moz-box-align属性。 Safari,Opera和Chrome支持另一种选择-webkit-box-align属性。 注意:Internet Explorer 9及早期版本不支持灵活框。