定位类型
/相对定位/
/position: relative;/
/绝对定位,让出位置b2,相对于上一个设置了定位的父级(body)定位/
position: absolute;
/以浏览器窗口为参照物定位,像浮动小广告/
position: fixed;
例子
position: absolute;
left: 50px;
bottom: 400px;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box{
width: 400px;
height:400px;
border:1px solid #000;
margin: 50px auto 0;
/*加入position,则根据此来定位*/
position: relative;
}
.b1 ,.b2,{
width: 300px;
height: 100px;
}
.b1{
background-color: gold;
/*相对定位*/
/*position: relative;*/
/*绝对定位,让出位置b2,相对于上一个设置了定位的父级(body)定位*/
position: absolute;
left: 50px;
bottom: 400px;
}
.b2{
background-color: green;
/*以浏览器窗口为参照物定位,像浮动小广告*/
position: fixed;
left: 50px;
bottom: 100px;
}
</style>
</head>
<body>
<div class="box">
<div class="b1"></div>
<div class="b2"></div>
<div class="b3"></div>
<div class="b4"></div>
</div>
</body>
</html>
实例
目的:固定在顶部的水平居中的菜单
注:绝对定位和固定定位的块元素和行内元素会自动转换为行内元素
/*水平居中技巧*/
left: 50%;
margin-left: 此块的一半 如-250px;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.menu{
width: 500px;
height: 50px;
background-color: gold;
position: fixed;
/*水平居中技巧*/
left: 50%;
margin-left: -250px;
}
</style>
</head>
<body>
<div class="menu">菜单</div>
<br>
<p>shuaihai</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>shuaihai</p>
<p>shuaihai</p>
br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p>shuaihai</p>
<p>shuaihai</p><p>shuaihai</p><p>shuaihai</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>应用消息显示</title>
<style type="text/css">
.con{
width: 100px;
height: 100px;
background-color: gold;
border-radius: 14px;
position: relative;
margin: 50px auto 0;
}
.box1{
width: 28px;
height: 28px;
border-radius: 14px;
background-color: red;
color: white;
line-height: 28px;
text-align: center;
position: absolute;
left: 86px;
top: -14px;
}
</style>
</head>
<body>
<div class="con">
<div class="box1">5</div>
</div>
</body>
</html>