七、盒子的定位
定位的基本思想很简单,它允许用户定义元素框相对于其正常位置应该出现的位置,这个属性定义建立元素布局所用的定位机制。
1.定位属性
(1).定位方式(position)
position属性可以选择4种不同类型的定位方式。语法如下:
position: static | relative | absolute | fixed
参数:static静态定位为默认值,无特殊定位,对象遵循HTML定位规则:relative生成相对定位的元素,相对于其正常位置进行定位;absolute生成绝对定位的元素,元素的位置通过left、top、right和bottom属性进行规定;fixed生成绝对定位的元素,相对于浏览器窗口进行定位,元素的位置通过left、top、right以及bottom属性进行规定。
(2).左、右、上、下位置
语法:
left: auto | length
right: auto | length
top: auto | length
bottom: auto | length
参数:auto无特殊定位,根据HTML定位规则在文档中分配;length是由数字和单位标识符组成的长度值或百分数。必须定义position属性为absolute或者relative,此取值方可生效‘。
(3).宽度(width)
语法:
width: auto | length
参数:auto无特殊定位,根据HTML定位规则在文档中分配;length是由数字和单位标识符组成的长度值或百分数,百分数是基于父对象的宽度,不可为负值。
(4).高度(height)
语法:
height: auto | length
参数:auto无特殊定位,根据HTML定位规则在文档中分配;length是由数字和单位标识符组成的长度值或百分数,百分数是基于父对象的宽度,不可为负值。
(5).最小高度(mini-height)
语法:
mini-height: auto | length
参数:auto无特殊定位,根据HTML定位规则在文档中分配;length是由数字和单位标识符组成的长度值或百分数,百分数是基于父对象的宽度,不可为负值。
(6).可见性
语法:
visibility: inherit | visible | collapse | hidden
参数:inherit继承上一个父对象的可见性;visible使对象可见,如果希望对象可见,其父对象也必须是可见的;hidden使对象被隐藏;collapse主要用来隐藏表格的行或列,隐藏的行或列能够被其他内容所使用,对于表格外的其他对象,其作用等同于hidden。
2.定位方式
(1)静态定位
静态定位使position属性的默认值,盒子按照标准流(包括浮动的方式)进行布局,即该元素出现在文档的常规位置,不会重新定位。
案例
<html>
<head>
<meta charset="utf-8">
<title>静态定位</title>
<style type="text/css">
body{
margin: 20px;
font: Arial 12px;
}
#father{
background-color: #a0c8ff;
border: 1px dashed#000000;
padding: 15px;
}
#block_one{
background-color: #fff0ac;
border: 1px dashed#000000;
padding: 10px;
}
</style>
</head><body>
<div id="father">
<div id="block_one">盒子1</div>
</div>
</body>
</html>
“盒子1”没有设置任何position属性,相当于是使用静态定位方式,页面布局也没有发生任何变化。
(2)相对定位
使用相对定位的盒子,会相对于自身原本的位置,通过偏移指定的距离到达新的位置。使用相对定位,除了要将position属性设置为relative外,还需要指定一定的偏移量。其中,水平方向的偏移量由left和right属性指定;竖直方向的偏移量是由top和bottom属性指定。
案例
<html>
<head>
<meta charset="utf-8">
<title>静态定位</title>
<style type="text/css">
body{
margin: 20px;
font: Arial 12px;
}
#father{
background-color: #a0c8ff;
border: 1px dashed#000000;
padding: 15px;
}
#block_one{
background-color: #fff0ac;
border: 1px dashed#000000;
padding: 10px;
position: relative;
left: 30px;
top: 30px;
}
</style>
</head><body>
<div id="father">
<div id="block_one">盒子1</div>
</div>
</body>
</html>