css总结(5)
层模型
层模型就是让元素在网页中精确定位,就像Photoshop中的图层一样可以对每一个图层精确定位
三种形式:
1.绝对定位(position: absolute)
2.相对定位(position: relative)
3.固定定位(position: fixed)
绝对定位
如果想为元素设置层模型中的绝对定位,需要设置position: absolute,这条语句的作用将元素从文档流中拖出来,然后使用left、right、top、bottom属性相对于其最接近的一个具有定位属性的父包含块进行绝对定位。如果不存在这样的包含块,则相对于body元素,即相对于浏览器窗口
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>例子</title>
<style type="text/css">
.demo{
position:absolute;/*脱离原来的位置进行定位*/
width:100px;
height:100px;
background-color:red;
opacity:0.5;/*设置透明度,便于观察*/
}
.box{
width:150px;
height:150px;
background-color:yellow;
}
</style>
</head>
<body>
<div class="demo">
</div>
<div class="box">
</div>
</body>
</html>
定位前
定位后
相对定位
为元素设置层模型中的相对定位,需要设置position: relative,它通过left、right、top、bottom属性确定元素在正常文档流中的偏移位置。相对定位完成的过程是首先按static(float)方式生成一个元素(并且元素像层一样浮动了起来),然后相对于以前的位置移动,移动的方向和幅度由left、right、top、bottom属性确定,偏移前的位置保留不动。(相对于自己原来的位置定位)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>例子</title>
<style type="text/css">
.demo{
position:relative;/*保留原来的位置进行定位*/
left:100px;
right:100px;
width:100px;
height:100px;
background-color:red;
opacity:0.5;/*设置透明度,便于观察*/
}
.box{
width:150px;
height:150px;
background-color:yellow;
}
</style>
</head>
<body>
<div class="demo">
</div>
<div class="box">
</div>
</body>
</html>
定位前
定位后
一般用relative作为参照物,用absoulute进行定位。
固定定位
:fixed
表示固定定位,与absolute定位类型类似,但它的相对移动的坐标是视图(屏幕内的网页窗口)本身。由于视图本身是固定的,它不会随浏览器窗口的滚动条滚动而变化,除非你在屏幕中移动浏览器窗口的屏幕位置,或改变浏览器窗口的显示大小,因此固定定位的元素会始终位于浏览器窗口内视图的某个位置,不会受文档流动影响,这与background-attachment: fixed;属于功能相同。(可以实现页面上的小广告)
例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>例子</title>
<style type="text/css">
div{
position:fixed;
width:100px;
height:100px;
background-color:#666;
left:0;/*通过left和top来改变在浏览器中的位置*/
top:200px;
}
</style>
</head>
<body>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div >
</div>
</body>
</html>
水平居中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>例子</title>
<style type="text/css">
div{
position:fixed;
left:50%;
top:50%;
width:100px;
height:100px;
background-color:red;
margin-left:-50px;/*因为定位是在方块的左上角,所以-50px让他移动到浏览器的正中间*/
margin-top:-50px;
}
</style>
</head>
<body>
<div >
</div>
</body>
</html>