定位之绝对定位

珠峰HTML|CSS精讲视频 admin 502浏览

定位元素>元素层级>元素定位>滚动条

绝对定位- position: absolute;特点

  1. 脱离文档流
  2. 可以设置参照物,参照物必须是其父级元素(直系父级),如果直接父级没有会一直往上查 找直到找到最外层的根元素为止
  3. 有宽度和高度的情况下,top和 bottom同时有值,top生效;left和 right同时有值,left生效;
  4. 没冇宽度和髙度的情况下,top和 bottom同时设置值的情况下,会将在这个盒子拉大,上下 值都起作用,左右同理;
  5. 可以设置层级关系z-index属性

绝对定位的特点:

  1. 它可以设置top、 bottom、left、 right四个方位值
  2. 绝对定位元素会脱离文档流不占位导致后面的元素会往前跑占领它的位置
  3. 绝对定位元素一定要有相对参照物(它的直接父级),如果父级元素没有加 相对参照物,它会一级一级往上查找,直到找到最外层的根元素htm1
  4. 如果方位里同时有1eft和 right最后听left;同时有top和 bottom最后听top 以后在实际项目中只需要设置top或者bottom 1eft或者 right
  5. z-index越大层级越在上
  6. 一个元素定位在一个元素上或者两个元素的叠加的这种情况;我们都可以用定位(绝对定位);绝对定位一定要指名它定位的方向
  7. 相对参照物只要是定位元素就可以(绝对定位,相对定位,固定定位);优先选相对定位 position: relative;绝对定位和固定定位都会脱离文档流不占位
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.red{
position: fixed;
/* position: relative; */

width: 500px;
height: 500px;
background-color: red;

margin-top: 100px;
margin: 50px auto;
}
.blue{
position: absolute;
top: 50px;
bottom: 80px;
left: 50px;
right: 80px;
width: 300px;
height: 300px;
background-color: blue;

z-index: 10;
}
.green{
width: 200px;
height: 200px;
background-color: green;

position: relative;
z-index: 11;
}

.pic{
width: 200px;
height: 200px;
margin: 0 auto;
position: relative;
}
.pic img{
display: block;
width: 100%;
height: 100%;
}
.pic .bg{
width: 200px;
height: 50px;
background-color: rgba(0,0,0,.5);
position: absolute;
bottom: 0;
left: 0;
}
.pic .txt{
position: absolute;
left: 0;
bottom: 0;
height: 50px;
line-height: 50px;
font-size: 14px;
color: #fff;
text-align: center;
width: 100%;
}
</style>
</head>
<body>
<div class="red">
<div class="blue"></div>
<div class="green"></div>
</div>

<div class="pic">
<img src="images/404.png" alt="">
<div class="bg"></div>
<div class="txt">1个元素定在另一个元素上面</div>
</div>

<div style="height: 1000px;"></div>
</body>
</html>

转载请注明:大灰牛博客 » 定位之绝对定位