d
k
p
l
u
s

写给后端的前端笔记:定位(position)

写给后端的前端笔记:定位(position)

既然都写了一篇浮动布局,干脆把定位(position)也写了,这样后端基本上能学会css布局了。

类别

我们所说的定位position主要有三类:固定定位fixed,相对定位relative,绝对定位absolute。它们都有相同的四个属性:topbottomleftright

区别

主要在于他们的参照物不一样

<div class="block" id="div1">固定定位bottom: 40px;<br>right: 40px;</div>
<div class="block" id="div2">相对于浏览器窗口的绝对定位<br>top: 20px;<br>right: 20px;</div>
<div class="block" id="div3">
相对定位    
    <div class="block" id="div4">相对于父元素的绝对定位<br>right: 10px;<br>top: 20px;</div>
</div>
<div class="block" id="div5">相对定位</div>
.block{
    width: 100px;
    height: 100px;
}

固定定位

固定定位的参照物是浏览器窗口,很多窗口广告就是用的固定定位,无论你怎么滚动或者放大缩小窗口,永远固定在浏览器窗口某个角落。

修改topbottomleftright的值可以调整元素在浏览器窗口的位置。

#div1{
    position: fixed;
    bottom: 40px;
    right: 40px;
    background: red;
}

绝对定位

绝对定位的参照物是该元素上一级的拥有position:relative属性的父元素,如果该元素的上一级父元素没有设置相对定位,那么该元素的参照物就会变成当前页面。

修改topbottomleftright的值可以调整元素在父元素内的位置。

#div2{
    position: absolute;
    top: 20px;
    right: 20px;
    background: green;
}
#div3{
    position: relative;
    width: 300px;
    height: 300px;
    background: blue;
}
#div4{
    position: absolute;
    right: 10px;
    top: 20px;
    background: yellow;
}

相对定位

相对定位的参照物是该元素本来的位置。

修改topbottomleftright的值可以让元素相对于原来的位置上下左右移动。

#div5{
    position: relative;
    top: -20px;
    right: -100px;
    background: grey;
}
posted @ 2017-09-04 08:36  dkplus  阅读(1383)  评论(10编辑  收藏  举报