简洁明了的CSS定位
Css定位:
Position属性规定应用于元素的定位方法的类型,有四种属性值,
元素其实是使用 top、bottom、left 和 right 属性定位的。但是,除非首先设置了 position 属性,否则这些属性将不起作用。根据不同的 position 值,它们的工作方式也不同。
1、 Position: static默认值,没有定位,
2、 Position: relative 相对定位
3、 Position: absolute 绝对定位
4、 Position:fixed 固定定位
1、 position:static默认值:元素默认情况下的定位方式为 static;元素不会以任何特殊方式定位
2、 position:relative 相对定位特性:
(1) 相对于自己的初始位置来定位
(2) 元素位置发生偏移后,它原来的位置会被保留下来,不会脱离标准文档流
(3) 相对于一般情况下很少自己单独使用,都是配合绝对定位使用,为绝对定位创造定位父级而又不设置偏移。
3、 Position: absolute 绝对定位特性:
(1) 绝对定位相对于它的父级来定位,如果没有设置父级,则相对于浏览器窗户来定位。
(2) 元素位置发生偏离后,原来的位置不会被保留
(3) 设置绝对定位的元素会脱离标准文档流
4、 Position:fixed 固定定位的特性:
(1) 相对于浏览器窗口来定位
(2) 偏移量不会随动移动而移动
(3) 一般在网页中被用在窗口左右两边的固定广告、返回顶部图标、吸顶导航栏等。
以下是代码和运行结果的前后对比:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
.position {
width: 1440px;
height: 300px;
margin: 0px auto;
border: 3px solid black;
/* 设置此为盒子相对定位,为绝对定位做父级*/
position: relative;
}
h1{
width: 1440px;
margin: 0px auto;
margin-top:20px;
}
.static1,
.relative1,
.absolute1,
.fixed1{
width:200px ;
height: 100px;
background-color: gainsboro;
float: left;
margin-right:10px;
}
.static2,
.relative2,
.absolute2,
.fixed2{
width:200px ;
height: 100px;
background-color: red;
float: left;
margin-right:10px;
}
/* static 默认值不做变动,不受bottom影响 */
.static2{
position: static;
top: 200px;
}
/* relative 相对于自己的初始位置来定位,配合绝对定位使用,为绝对定位创造定位父级而又不设置偏移。 */
.relative2{
position: relative;
top: 200px;
}
/* (1) 绝对定位相对于它的父级来定位,如果没有设置父级,则相对于浏览器窗户来定位;(2)设置绝对定位的元素会脱离标准文档流 */
.absolute2{
position: absolute;
top: 200px;
}
/* (1) 相对于浏览器窗口来定位(2)不会随网页滚动条的移动而移动(3) 一般在网页中被用在窗口左右两边的固定广告、返回顶部图标、吸顶导航栏等 */
.fixed2{
position: fixed;
right: 0px;
background-color: red;
}
</style>
</head>
<body>
<div class="position">
<div class="static1">static没有定位</div>
<div class="relative1">relative相对定位</div>
<div class="absolute1">absolute绝对定位</div>
<div class="fixed1 ">fixed固定定位</div>
</div>
<h1>定位后</h1>
<div class="position">
<div class="static2">static不受上下左右的影响</div>
<div class="relative2">relative移动后</div>
<div class="absolute2">absolute以盒子为父级移动后</div>
<div class="fixed2 ">fixed 固定在浏览器窗口指定位置</div>
</div>
</body>
</html>
以下是运行代码