定位(position)
CSS 为定位和浮动提供了一些属性,利用这些属性,前端设计师可以设计更好的界面,进行页面的渲染。定位属性可以使相关的元素进行页面上的调整或者在div块内进行调整,可以说功能非常的强大。
盒子模型
1. Margin(外边距) - 清除边框外的区域,外边距是透明的。
2. Border(边框) - 围绕在内边距和内容外的边框。
3. Padding(内边距) - 清除内容周围的区域,内边距是透明的。
4. Content(内容) - 盒子的内容,显示文本和图像。
- css中4种常见的div边距设置方法
- margin/padding: Apx Bpx Cpx Dpx;(上,右,下,左)
- margin/padding: Apx Bpx Cpx;(上,左&右,下)
- margin/padding: Apx Bpx;(上&下,左&右)
4 margin/padding: Apx (上&下&左&右)
- border的常见设置方式
border:__px solid(实线)/dotted(原点)/dashed(虚线) 颜色
1.静态定位(static)
position:static是所有元素定位的默认值, 一般不用注明,有浏览器默认给出位置,除非有需要取消继承的别的定位。
注意,static定位所导致的元素位置,是浏览器自主决定的,如果在css样式中写入position:static,这时top、bottom、left、right这四个属性无效。
2.相对定位(relative)
position:relative是相对于默认位置(即static时的位置)进行偏移,即定位基点是元素的默认位置。它必须搭配top、bottom、left、right这四个属性一起使用,用来指定偏移的方向和距离。
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- <link rel="stylesheet" href="css/demo.css"> -->
<style type="text/css">
.box {
/* background: rgb(166, 255, 0); */
width: 100px;
height: 100px;
float: left;
margin: 5px;
}
.two {
position: relative;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="box" style="background: rgb(166, 255, 0);">One</div>
<div class="box two" style="background: rgb(255, 187, 0);">Two</div>
<div class="box" style="background: rgb(98, 0, 255);">Three</div>
<div class="box" style="background: rgb(255, 0, 43);">Four</div>
</body>
</html>
结果:
结论:
上面代码中,div元素从默认位置(static)向右偏移50px(即距离左侧50px)、向下偏移50px(即距离顶部50px)。
##注意:相对定位会改变其他div的布局
3.绝对定位(absolute)
position:absolute绝对定位使用通常是父级定义position:relative定位,子级定义position:absolute绝对定位属性,并且子级使用left或right和top或bottom进行绝对定位。
它有一个重要的限制条件:定位基点(一般是父元素)不能是static定位,否则定位基点就会变成整个网页的根元素html。即如果元素的父级没有设置定位属性,则依据 body 元素左上角作为参考进行定位。
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- <link rel="stylesheet" href="css/demo.css"> -->
<style type="text/css">
.box {
/* background: rgb(166, 255, 0); */
width: 100px;
height: 100px;
float: left;
margin: 5px;
}
.two {
position: absolute;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div class="box" style="background: rgb(166, 255, 0);">One</div>
<div class="box two" style="background: rgb(255, 187, 0);">Two</div>
<div class="box" style="background: rgb(98, 0, 255);">Three</div>
<div class="box" style="background: rgb(255, 0, 43);">Four</div>
</body>
</html>
结果:
结论:
上面代码中,div元素从默认位置(static)向右偏移50px(即距离左侧50px)、向下偏移50px(即距离顶部50px)。
##注意:绝对定位不会改变其他div的布局
4.固定定位(fixed)
固定定位与绝对定位类似,但它是相对于浏览器窗口定位,并且不会随着滚动条进行滚动。无需设置top、bottom、left、right。
div {
position: fixed;
top: 0;
}
结果:
在上述的代码中,div块始终在浏览器视口的顶部,不会碎滚动条的滚动而变化
其实还有一个static属性,可以形成动态效果,就像是relative和fixed的结合,一些时候是relative定位(定位基点是自身默认位置),另一些时候自动变成fixed定位(定位基点是视口)。我会在下次博客重点介绍。