前言
css样式中,也有一个像iOS的layout
一样的布局方式,那就是position
;
position
中,通过设置left
、right
、top
、bottom
来进行布局,但一般情况下,这四个属性都不起作用,只有设置了position
才行;
position
position
属性的几个值(static
、fixed
、relative
、absolute
、sticky
、)
-
static:
设置后,元素不受left
、right
、top
、bottom
影响; -
fixed:
设置元素相对于浏览器窗口的位置,即使窗口移动,元素的位置也不会发生变化; -
relative:
设置元素相对于其正常的位置的偏移,值可正可负;
<div class="content" style="background-color: red;">正常</div>
<div class="content left" style="background-color: green;">向左偏移</div>
<div class="content right" style="background-color: blue;">向右偏移</div>
...
.content {
width: 400px;
height: 30px;
text-align: center;
color: white;
position: relative;
}
.left {
left: -30px;
}
.right {
left: 30px;
}

-
absolute:
设置元素相对于最近的已定位父元素的位置,和iOS的layout
一样;
父元素不能是static,否则absolute就会和fixed一样了;
<div class="bg">
<div class="content">正常</div>
</div>
.bg {
background-color: gray;
width: 500px;
height: 100px;
position: absolute; // 必须设置position
left: 100px;
top: 300px;
}
.content {
background-color: red;
color: white;
position: absolute;
top: 10px;
left: 20px;
bottom: 10px;
right: 20px;
text-align: center;
}

absolute是设置对于最近的已定位父元素的位置,如果所有的父元素都没有设置
position
定位,那就是相对于<html>的;
额外
通过position也可设置元素的居左对齐,或居右对齐。
网友评论