css当中的position定位
大约 2 分钟
提示
定位文档流和浮动流不一样,定位文档流可以覆盖浮动流,浮动流不能定位.
absolute:绝对定位相对于父级(需要父级也是定位的)或(0px,0px)定位.有top/left/right/bottom属性.可以给负值.
绝对定位脱离文档流,可以覆盖浮动流.其他元素会补位.
relattive:相对定位,是相对于元素自身为参考原点定位.相对定位移动后,其他元素不会补位.
fixed:固定定位,是相对于我们可视化的窗口来定位的.所以可以top left right bottom属性用.
示例:
<!DOCTYPE html>
<html>
<head>
<title>css当中的position定位</title>
<meta charset="utf-8" />
<link href="" type="text/css" rel="stylesheet" />
<style>
div{
width:250px;
height:250px;
border:1px solid red;
}
#one{
background:red;
}
#two{
background:green;
/*将绿色的div设置为绝对定位*/
position:absolute;
/*进行位置调整*/
left:150px;
top:200px;
/*right:0px;
bottom:0px;*/
/*延z轴进行位置调整*/
/*z-index:-1;*/
}
#three{
background:blue;
/*相对定位*/
position:relative;
}
#three #small{
width:50px;
height:50px;
background:pink;
/*绝对定位*/
position:absolute;
/*进行移动*/
left:50px;
top:50px;
}
#window{
width:300px;
height:200px;
text-align:center;
border:1px solid red;
/*固定定位*/
position:fixed;
right:0px;
bottom:0px;
}
#window #close{
width:20px;
height:20px;
border:1px solid red;
}
</style>
</head>
<body style="height:2000px;">
<!--
文档流:我们通常在看一个网站时,网站内容的排版自上而下显示的内容,都是在一个叫做文档流的
东西当中,使用position定位,可以将网页中的某些元素脱离正常文档流,独立存在,他们
互不干扰!
-->
<h1>它可以定位任何html元素</h1>
<div id="one"></div>
<div id="two"></div>
<div id="three">
<div id="small"></div>
</div>
<div id="window">
<div id="close">×</div>
<a href="./bg/2.jpg">点击我,可以看你想看的东西!</a>
</div>
<script>
// 获取id为close的元素,并且存放到一个变量中
var but = document.getElementById('close');
var win = document.getElementById('window');
//当鼠标移入but这个按钮时,让鼠标变成小手
but.onmouseover = function(){
but.style.cursor = 'pointer';
}
//当鼠标点击but按钮时,让window这个div隐藏
but.onclick = function(){
win.style.display = 'none';
}
</script>
</body>
</html>