CSS -- 定位
CSS 中最重要的应该就是布局和定位, 也就是 display 和 position 两个属性.
讲布局之前, 先说一下 CSS 的框模型 Box Model, 它规定了元素框处理 元素内容, 内边距, 边框和外边距的方式
框模型
Box Model
外边距合并
外边距合并意思就是当两个垂直的外边距相遇时, 会合并成一个外边距, 合并之后外边距的高度是两个外边距中较大的一个.
外边距合并 1
当一个元素包含在另一个元素中时(假设没有内边距或边框把外边距分隔开), 它们的上和 / 或下外边距也会发生合并.
外边距合并 2
文档流
元素按照 html 中的位置顺序元素, 块元素 (block) 独占一行, 内联元素(inline), 不独占一行
定位
CSS 的定位主要是靠 position 这个属性, 它有以下五种选择
- static
- relative
- fixed
- absolute
- sticky
static - 静态定位
元素默认的 position 属性, 浏览器会根据源码的顺序, 决定每个元素的位置, 就是正常的文档流. 每个区块占据自己的位置, 不会发生重叠(同级区块). 并且此时 left,right,top,bottom 的属性是无效的, 元素的位置由浏览器自主决定.
static.jpg
relative - 相对定位
相对定位是在静态定位的基础上进行偏移. 偏移是根据 left,right,top,bottom 四个属性决定方向和距离.
relative.jpg
此时, 元素依然处于文档流中, 而且, 相对定位是不会影响文档流的.
举个例子,
- <style type="text/css">
- .parent {
- border: 2px solid red;
- }
- .parent div {
- height: 100px;
- width: 100px;
- background-color: red;
- margin-bottom: 10px;
- text-align: center;
- }
- .div2 {
- position: relative;
- background-color: orange !important;
- top: 200px;
- left: 20px;
- }
- </style>
- <div class="parent">
- <div class="div1">test1</div>
- <div class="div2">test2</div>
- <div class="div3">test3</div>
- </div>
relative-demo.PNG
div2 的位置虽然有偏移, 但是父元素并没有受其影响, 就是说它在文档流中的位置还是和静态布局的位置一样, 只是显示的时候有偏移.
absolute - 绝对定位
绝对定位是根据第一个定位不为 static 的父元素进行偏移. 如果没有不为 static 的父元素, 则根据整个网页的根元素 HTML 进行偏移, 偏移的方向和距离根据 left,right,top,bottom 四个属性决定. 绝对定位不会影响页面中的其他元素
就如刚才的例子, 如果把 div2 的定位设为绝对定位, 则文档流中只有 div1 和 div3.
absolute-demo.PNG
fixed - 固定定位
固定定位是类似于绝对定位, 但是是相对于浏览器窗口定位, 而且不会受到滚动条的影响.
Example
sticky - 粘性定位
粘性定位可以说是相对定位和固定定位的组合, 就是可以自动切换相对定位 / 固定定位. 它主要用在对 scroll 事件的监听上; 简单来说, 在滑动过程中, 某个元素距离其父元素的距离达到粘性定位的要求时(比如 top:10px), 这时其效果相当于 fixed 定位, 固定到适当位置.
- Example1
- Example2
使用条件:
必须搭配 top,bottom,left,right 其一使用, 否则相当于相对定位
父元素的 overflow 不能为 hidden 或者 overflow
父元素的高度不能低于 sticky 元素的高度
sticky 元素仅在其父元素内生效
- <!DOCTYPE HTML>
- <HTML>
- <head>
- <title>
- position
- </title>
- <style type="text/css">
- .stacking-slide { height: 100vh; width: 100%; position: sticky; top: 0;
- } .stacking-slide:nth-child(1) { background-color: #ffc2c2; } .stacking-slide:nth-child(2)
- { background-color: #ffe0c2; } .stacking-slide:nth-child(3) { background-color:
- #ffffc2; } .stacking-slide:nth-child(4) { background-color: #e0ffc2; }
- .stacking-slide:nth-child(5) { background-color: #c2ffc2; }
- </style>
- </head>
- <body>
- <div class="stacking-slide">
- <h2>
- Section 1
- </h2>
- </div>
- <div class="stacking-slide">
- <h2>
- Section 2
- </h2>
- </div>
- <div class="stacking-slide">
- <h2>
- Section 3
- </h2>
- </div>
- <div class="stacking-slide">
- <h2>
- Section 4
- </h2>
- </div>
- <div class="stacking-slide">
- <h2>
- Section 5
- </h2>
- </div>
- </body>
- </HTML>
来源: http://www.jianshu.com/p/0fb383a0aefa