绝对定位+负边距
上一小节我们讲了利用绝对定位来进行居中布局。本小节继续讲另外一种实现居中布局。
但注意,本小节的"绝对定位+负边距"这种不适合绝对定位法那种宽百分之多少、高百分之多少这种相对单位,取而代之的是具体的数值。
比如,这个例子我们设置居中的盒子宽度为 300px、高度为 200px:
<!DOCTYPE html>
<html>
<head>
< charset="UTF-8">
< name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 清除认样式 */
* { padding: ; margin: ; }
/* 令html和body全屏, 并有灰色背景 */
html, body { height: ; background: gray; }
/* 先在父元素上设置相对定位 */
body { position: relative }
.center {
/* 绝对定位 */
position: absolute;
/* 上方和左方为50% */
top: ;
left: ;
/* 给定宽高 */
width: px;
height: px;
/* 上外边距为负的给定高度的一半 */
margin-top: -px;
/* 左外边距为负的给定宽度的一半 */
margin-left: -px;
/* 白色背景 */
background: white;
}
</style>
</head>
<body>
<div class="center"></div>
</body>
</html>
运行结果: