理解position四大定位方式
absolute:位置设置为 absolute 的元素,可定位于相对于第一个已定位(非静态的)的包含它的元素的指定坐标。此元素的位置可通过 “left”、“top”、“right” 以及 “bottom” 属性来规定。
relative:位置被设置为 relative 的元素,可将其定位于相对于其正常位置的地方,因此 “left:20” 会将元素移至元素正常位置左边 20 个像素的位置。
position:relative
position:absolute
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS-position-relative</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/normalize/8.0.0/normalize.css">
<style>
.title{
height: 100px;
}
.out{
width:200px;
height: 200px;
position: relative;
top: 100px;
background-color: #ff0000;
}
</style>
</head>
<body>
<div class="title">
<p>wwwwwwwwww </p>
</div>
<div class="out"></div>
</body>
</html>
给out设置position:relative属性,top:100px,
距离顶部200px,因为不脱离文档流,不可以覆盖title的高度。
给out设置position:absolute属性,top:100px,
距离顶部100px,因为脱离文档流,不受title高度的影响。
总结:absolute:不占位、relative:有占位!
absolute
fixed:位置被设置为 fixed 的元素,可定位于相对于浏览器窗口的指定坐标。此元素的位置可通过 “left”、“top”、“right” 以及 “bottom” 属性来规定。不论窗口滚动与否,元素都会留在那个位置。工作于 IE7(strict 模式)。
static: 默认。位置设置为 static 的元素,它始终会处于页面流给予的位置(static 元素会忽略任何 top、bottom、left 或 right 声明)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS-position-relative</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/normalize/8.0.0/normalize.css">
<style>
html,body{
height: 120%;
}
.title{
height: 100px;
}
.out{
width:200px;
height: 200px;
position: fixed;
top: 100px;
background-color: #ff0000;
}
</style>
</head>
<body>
<div class="title">
<p>wwwwwwwwww </p>
</div>
<div class="out"></div>
</body>
</html>
position:fixed
title随着滚动条滚动,因为脱离文档流,out不随滚动条滚动,
一直固定在那个位置。
posotion:static
给out设置static,因为不脱离文档流,out随着滚动条滚动,但是给top,left,right,bottom属性赋值,不改变样式。浏览器默认值就是static