css3定位属性
top,bottom,left,right
- 取值:auto,,
- 默认值:auto
- 继承性:无
说明
- 定义了元素的上外边距边界(外margin)与其包含块上边界(外padding)之间的偏移距离,取值可以为负值;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
padding: 0;
margin:0;
}
.parent1{
width:100px;
height:100px;
position:relative;
padding: 10px;
margin:20px;
border: 15px solid #ddd;
}
.child1{
width:20px;
height: 20px;
top:30px;
position:absolute;
padding: 10px;
margin:20px;
border: 25px solid #ccc;
}
</style>
</head>
<body>
<div class="parent1">
<div class="child1"></div>
</div>
</body>
</html>
- 当position为static时,计算值是auto。为relative时,如果top和bottom都是auto,则它们的计算值是0;如果top和bottom其中一个为auto,则auto相当于另一个的负值,即top=-bottom;如果top和bottom的值都不为auto,则忽略bottom(left和right)。
注意:
- 绝对定位的布局取决于三个因素,一个是元素的位置,一个是元素的尺寸,一个是元素的margin值。
- 没有设置尺寸和 margin的元素会自适应剩余空间,位置固定则分配尺寸,尺寸固定边会分配 margin,都是自适应的。
利用上述特性,我们可以利用有如下的方法实现元素的水平垂直居中效果。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
padding: 0;
margin:0;
}
.parent1{
width:100px;
height:100px;
position:relative;
border: 1px solid #ddd;
}
.child1{
width:20px;
height: 20px;
background-color: red;
position:absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto; //后面六个css属性中,position:absolute,margin:auto不能缺少,如果只有top和bottom,则只能实现垂直居中;如果只有left和right,则只能实现水平居中;如果四个都有,能够实现水平垂直居中
}
</style>
</head>
<body>
<div class="parent1">
<div class="child1"></div>
</div>
</body>
</html>
参考链接: