您现在的位置是: 首页 > 技术分享 >
作为一个后端开发人员,对css中的定位始终搞不明白,也不知如何使用。最近才发现,原来我不愿意触碰的知识点,只要用点心,就可以完全掌握,并且应用到实际项目中。回归正题,今天这篇就详细写一下关于页面布局常用到的定位问题,记录的本身就是为巩固已学过的知识,学而不思则罔,思而不学则殆。
在DOM中,静态定位即没有定位,不可以设置偏移值(偏移值属性有:left、top、bottom、right),且元素在文档流中。如果我们不设置的话,任何元素的position属性默认值都是static。
<meta charset="UTF-8">
<title>static和relatiive定位</title>
<style>
.wrapper {
width: 600px;
height: 400px;
border: 1px solid #cccccc;
margin: 0px auto;
}
.box1,.box2,.box3{
width: 150px;
height: 150px;
border: 1px dotted #ff5529;
display: inline-block;
}
.box2{
position: relative;
left: 10px;
top: 100px;
}
</style>
<div class="wrapper">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
第三种:绝对定位(position:absolute)
一般来说,绝对定位和相对定位结合使用,它相对的父级是对于relative定义的元素。relative元素必须是absolute的父级
<meta charset="UTF-8">
<title>absolute</title>
<style>
.wrapper {
width: 600px;
height: 400px;
border: 1px solid #cccccc;
margin: 0px auto;
position: relative;
}
.box1,.box2,.box3{
width: 150px;
height: 150px;
border: 1px dotted #ff5529;
display: inline-block;
}
/*相对定位*/
.box2 {
position: absolute;
left: 10px;
top: 10px;
}
</style>
<div class="wrapper">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
第四种:fixed 固定定位
应用场景:固定导航(在浏览网页中,设置fixed导航,用户可以轻松回到顶部,增强用户体验感)
<meta charset="UTF-8">
<title>fixed定位</title>
<style>
.wrapper {
width: 600px;
height: 400px;
border: 1px solid #cccccc;
margin: 0px auto;
}
.box1,.box2,.box3{
width: 150px;
height: 150px;
border: 1px dotted #ff5529;
display: inline-block;
}
.box2{
position: fixed;
left: 100px;
top: 100px;
}
</style>
<div class="wrapper">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</div>
以上,就是对定位的应用。其中,有两个脱离文档流的,分别是绝对定位和固定定位,但是绝对定位的偏移量是相对于body的,而固定定位的偏移量是相对于浏览器左上角坐标的。有两个占用标准流的,分别是静态定位和相对定位,静态定位是元素定位的默认值,不可以设置偏移量。相对定位可以设置偏移量,但相对自身所占的位置设置的。
在日常项目开发中,相对定位和绝对定位结合使用。而在导航固定的场景中,一般使用fixed固定定位。关于定位的问题,还需要在实际项目中开发中灵活应用。
如果想设置某个元素为绝对定位时,一定要找到其父级设置定位为relative。
下一篇: 写给入门或是技术遇到瓶颈期的小伙伴们
