定义width
矩形并使用margin: 0 auto;
它在页面中水平居中。
如果你想div
水平和垂直居中,使用这样的东西
HTML
<div id="rectangle"></div>
CSS
#rectangle {
width: 30%; //can set any value here
height: 20%; //can set any value here
position: absolute;
left: 50%;
top: 50%;
margin-left: -15%; //negative half of width
margin-top: -10%; //negative half of height
background-color: red;
}
看这里的小提琴。
或者
HTML
<div id="wrapper">
<div id="container">
<div id="rectangle"></div>
</div>
</div>
CSS
body, html {
height: 100%;
overflow:hidden;
}
#wrapper {
width: 100%;
height: 100%;
overflow: visible;
position: relative;
}
#wrapper[id] {
display: table;
position: static;
}
#container[id] {
display: table-cell;
vertical-align: middle;
width: 100%;
}
#rectangle {
width: 200px;
height: 100px;
margin-left: auto;
margin-right: auto;
background-color: blue;
}
看这里的小提琴。