您的位置:首页 > Web前端 > CSS

CSS控制元素定位

2016-10-29 12:13 399 查看
元素定位属性:position:static | absolute | fixed |relative;

static

元素按自身默认方式显示,并没有什么卵用

absolute

绝对定位,按照父元素为基准,进行偏移,如果没有父元素,就以body元素为基准定位。一定要记住是相对于父元素的定位 !position元素是漂浮起来的,有可能会覆盖到其他的正常元素

这里简单讲一下偏移属性,有四个

top|right|bottom|left  :  auto | length | percent


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>position</title>
<style>
div{
position:absolute;
width:100px;
height:50px;
border:2px solid #F00;
left:50px;
top:40px;
}

</style>
</head>

<body>
<div>
这里使用了position定位
</div>
</body>
</html>


relative相对定位,相对于自身的定位,自己本身没有定位前的位置就是默认位置,相对于默认值定位。比如两个div,本来的情况是一个盒子占一行,如果后面的div给了个相对定位,那么他的移动基准就是自己本来在的位置。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>position</title>
<style>
.Demo{
width:100px;
height:50px;
border:2px solid #00F;
}
.Demo2{
position:relative;
width:100px;
height:50px;
border:2px solid #F00;
left:50px;
top:40px;
}

</style>
</head>

<body>
<div class="Demo"></div>
<div class="Demo2"></div>
</body>
</html>


fixed

固定定位,他也是以一个元素为基准的,不过这个基准是你当前的视图窗口,也就是说,如果有下拉条的情况下,你的fixed元素是会跟着你的滑动而移动的,而且他也是浮动的,有可能覆盖到其他的元素。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>position</title>
<style>
.Demo{
width:100px;
height:50px;
border:2px solid #00F;
background:#0F0;
}
.Demo2{
position:fixed;
width:100px;
height:50px;
border:2px solid #F00;
left:50px;
top:40px;
background:#00F;
}

</style>
</head>

<body>
<div class="Demo"></div>
<div class="Demo2"></div>
<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/>
</body>
</html>


这里加了很多
目的是为了有下拉条。

未完待续……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: