关于定位,就是把某个对象固定再页面的特定地方,不管页面其他显示如何变化,都不会影响到该对象。
定位-position
书写语法 | 说明 | 文档流 | 偏移位置时候的参照物(top left right bottom) |
position:static; | 默认值 | 默认 | 默认 |
position:absolute; | 绝对定位 | 脱离 | 没有父元素的时候,参照物是浏览器的第一屏;有父元素且父元素有定位的时候 |
position:relative; | 相对定位 | 不脱离 | 自己的初始位置 |
position:fixed; | 固定定位 | 脱离 | 浏览器的当前位置 |
position:sticky: | 粘性定位 | ||
z-index:设置元素的层级,数值越大,层级越靠上 |
position:relative;
相对初始位置,下面的盒子仍然保持默认值,不会占用它原有的空间,但它会去占下面的空间。
.b{
background-color: rgb(11, 3, 255);
position: relative;
top:100px;
left: 100px;
/* 单独设置定位也无效,需要同时设置宽高 */
}
position:absolute;
脱离文档流,“与世无争”并且空出了初始位置,在其他元素设置的时候不会受到影响,也不会去影响到他们,默认优先(index)较高。会产生覆盖效果。
.a{
background-color: red;
position: static;
top: 100px;
/* 在静态定位下设置宽高无效 */
}
.c{
background-color: rgb(0, 255, 47);
position: absolute;
top: 100px;
left: 100px;
}
在有父元素的情况下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0px;
margin: 0px;
}
.box{
background-color: bisque;
width: 500px;
height: 500px;
margin: auto;
position: relative;
top: 50px;
}
.a{
background-color: brown;
width: 200px;
height: 200px;
position: absolute;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="box">
<div class="a"></div>
</div>
</body>
</html>
position:fixed;
永远将此对象固定在浏览器第一屏的某一位值。不会随着屏幕的滚动而改变。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0px;
margin: 0px;
}
.box{
background-color: bisque;
width: 100%;
height: 15000px;
margin: auto;
position: relative;;
}
.a{
background-color: brown;
width: 200px;
height: 200px;
position: fixed;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="a"></div>
</body>
</html>
position:sticky
粘性定位,当滚动到它的位置时,就会进行固定。
设置透明度
opacity:0-1;
让一个盒子在另一个盒子中居中
在给子元素相对父元素定位时,切记要给父元素设置相对定位,让子元素找到对齐目标,在子元素中的top,bottom,right,left是相对于父元素来说的的,前面带上margin-才是基于子元素的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
padding: 0px;
margin: 0px;
}
.box1{
margin: 0 auto;
width: 500px;
height: 500px;
background-color: bisque;
position: relative;
}
.box2{
width: 200px;
height: 200px;
background-color: aquamarine;
position: absolute;
top: 50%;
left: 50%;
/* 此时的top,left的比例是对于父盒子的大小而言的 */
margin-top: -100px;
margin-left: -100px;
/* 此时( margin-)的top,left的比例是对于自己的大小而言的 */
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
浮动和定位的区别
float:半脱离,可以让文字环绕。
absolute:全脱,不会出现环绕效果。