(3)绝对定位
使用绝对定位的盒子以它的“最近”的一个“已经定位”的“祖先元素”为基准进行偏移。如果没有已经定位的祖先元素,就以浏览器窗口为基准进行定位。
<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;
}
#block_two{
background-color: #fff0ac;
border: 1px dashed#000000;
padding: 10px;
position: absolute;
top: 0;
right: 0;
}
#block_three{
background-color: #fff0ac;
border: 1px dashed#000000;
padding: 10px;
position: relative;
}
</style>
</head><body>
<div id="father">
<div id="block_one">盒子1</div>
<div id="block_two">盒子2</div>
<div id="block_three">盒子3</div>
</div>
</body>
</html>
父容器中包含3个使用相同定位的盒子。接下来,只修改“盒子2”的定位方式为绝对定位,代码如下:
#block_two {
background-color: #fff0ac;
border: 1 px dashed #000000;
padding: 10px;
position: absolute;
tap: 0;
right: 0;
}
怎样才能让“盒子2”以id="father"的父容器为基准进行定位呢?只需要为该父容器设置定位方式即可,修改id="father"的父容器的CSS定义,代码如下:
#father {
background-color: #a0c8ff;
border: 1px dashed #000000;
padding: 15px;
position: relative;
}
重新浏览网页,“盒子2”偏移至id="father"父容器的右上角。还可以修改“盒子2”CSS定义中的水平、垂直偏移量,改变元素在祖先元素中的相对位置。代码如下:
#black_two {
background-color: #fff0ac;
border: 1px dashed #000000;
padding: 10px;
position: absolute;
top: 10px;
right: 50px;
}
(4)固定定位
固定定位(position:fixed)其实是绝对定位的子类别,一个设置了position:fixed的元素是相对于视窗固定的,就算页面文档发生了滚动,他也会一直待在相同的地方。
<html>
<head>
<meta charset="utf-8">
<title>演练5-12</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;
}
#block_two{
background-color: #fff0ac;
border: 1px dashed#000000;
padding: 10px;
position: fixed;
top: 0;
right: 0;
}
#block_three{
background-color: #fff0ac;
border: 1px dashed#000000;
padding: 10px;
position: relative;
}
</style>
</head><body>
<div id="father">
<div id="block_one">盒子1</div>
<div id="block_two">盒子2</div>
<div id="block_three">盒子3</div>
</div>
</body>
</html>