定位 position
position 属性的五个值:
- static
- fixed
- relative
- absolute
- sticky
static静态定位
HTML 元素的默认值,即没有定位,遵循正常的文档流对象。
静态定位的元素不会受到 top, bottom, left, right影响
<!DOCTYPE html>
<html>
<head>
<title>静态定位</title>
<meta charset="utf-8"/>
<style type="text/css">
div.static{
position:static;
top:20px;
width:200px;
height:200px;
border:1px solid red;
}
</style>
</head>
<body>
<div class="static">我是静态定位</div>
</body>
</html>
fixed 固定定位
Fixed 定位在IE7和IE8下需要描述!DOCTYPE才能支持。
Fixed定位使元素的位置与文档流无关,因此不占据空间。
Fixed定位的元素和其他元素重叠
<!DOCTYPE html>
<html>
<head>
<title>固定定位</title>
<meta charset="utf-8"/>
<style type="text/css">
div.fixed{
width:1000px;
height:800px;
background-color:green;
}
p{
position:fixed;
top:20px;
right:20px;
}
</style>
</head>
<body>
<div class="fixed">我是固定定位</div>
<p>砥砺奋进</p>
</body>
</html>
relative 相对定位
相对定位元素的定位是相对其正常位置。
移动相对定位元素,但它原本所占的空间不会改变
<!DOCTYPE html>
<html>
<head>
<title>相对定位</title>
<meta charset="utf-8"/>
<style type="text/css">
div{
width:300px;
height:300px;
border:1px solid red;
}
.relative1{
position:relative;
right:300px;
top:300px;
background-color:pink;
}
.relative2{
background-color:cyan;
}
</style>
</head>
<body>
<h1>css属性之相对定位</h1>
<div class="relative1">盒子1</div>
<div class="relative2">盒子2</div>
</body>
</html>
absolute 绝对定位
绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于:
absolute 定位使元素的位置与文档流无关,因此不占据空间。
absolute 定位的元素和其他元素重叠
<!DOCTYPE html>
<html>
<head>
<title> 绝对定位</title>
<meta charset="utf-8"/>
<style type="text/css">
div{
width:300px;
height:300px;
border:1px solid red;
}
.absolute1{
background-color:pink;
position:absolute;
}
.absolute2{
background-color:cyan;
position:absolute;
}
</style>
</head>
<body>
<h1>css属性之绝对定位</h1>
<div class="absolute1">盒子1</div>
<div class="absolute2">盒子2</div>
</body>
</html>
sticky 粘性定位
<!DOCTYPE html>
<html>
<head>
<title>定位</title>
<meta charset="utf-8"/>
<style type="text/css">
div.sticky1{
border:1px solid red;
background-color:pink;
height:50px;
width:300px;
line-height:50px;
text-align:center;
position:sticky;
top:10px;
}
div.sticky2{
padding-bottom:1000px;
}
</style>
</head>
<body>
<h1>css属性之粘性定位</h1>
<div class="sticky1">粘性定位之小猪进圈</div>
<div class="sticky2">
<p>1只猪</p>
<p>2只猪</p>
<p>3只猪</p>
<p>4只猪</p>
<p>5只猪</p>
<p>6只猪</p>
<p>7只猪</p>
</div>
</body>
</html>