1、常见的水平垂直居中实现方案
最简单的方案是flex布局
| .container{ |
| display: flex; |
| align-items: center; |
| justify-content: center; |
| } |
复制
绝对定位配合margin:auto(一定要给.son宽高)
| .father { |
| position: relative; |
| height: 300px; |
| } |
| .son { |
| position: absolute; |
| top: 0; |
| right: 0; |
| bottom: 0; |
| left: 0; |
| margin: auto; |
| width: 50px; |
| height: 50px; |
| } |
复制
绝对定位配合transform实现
| .father { |
| position: relative; |
| } |
| .son { |
| position: absolute; |
| top: 50%; |
| left: 50%; |
| transform: translate(-50%, -50%); |
| } |
| |
复制
2、行内元素,块级元素,空(void)元素(即没有内容的HTML元素)
块级元素: div、ul、li、dl、dt、dd、p、h1-h6、blockquote
行内元素: a、b、span、img、input、strong、select、label、em、button、textarea
空元素: br、meta、hr、link、input、img
3、BFC元素
我们在页面布局的时候,经常出现以下情况:
- 这个元素高度怎么没了?
- 这两栏布局怎么没法自适应?
- 这两个元素的间距怎么有点奇怪的样子?
- ......
原因是元素之间相互的影响,导致了意料之外的情况,这里就涉及到
BFC概念
BFC(Block Formatting Context)
即块级格式化上下文,它是页面中的一块渲染区域,并且有一套属于自己的渲染规则:
- 内部的盒子会在垂直方向上一个接一个的放置
- 对于同一个BFC的俩个相邻的盒子的margin会发生重叠,与方向无关。
- 每个元素的左外边距与包含块的左边界相接触(从左到右),即使浮动元素也是如此
- BFC的区域不会与float的元素区域重叠
- 计算BFC的高度时,浮动子元素也参与计算
- BFC就是页面上的一个隔离的独立容器,容器里面的子元素不会影响到外面的元素,反之亦然
如何生成一个BFC元素呢
- 根元素,即HTML元素
- 浮动元素:float值为left、right
- overflow值不为 visible,为 auto、scroll、hidden(常用)
- display的值为inline-block、inltable-cell、table-caption、table、inline-table、flex、inline-flex、grid、inline-grid
- position的值为absolute或fixed
常用于以下3个场景
- 防止margin重叠(塌陷)
- 自适应多栏布局
- 清除内部浮动
防止margin重叠(塌陷)
正常情况下,如果没有.container容器那么两p间隔是100px,这就是margin重叠了,解决方案就是给其中一个p套上一个BFC(div加上overflow: hidden;),那么两p间隔是200px了
| <style> |
| .container { |
| overflow: hidden;// 新的BFC |
| } |
| p { |
| color: #f55; |
| background: #fcc; |
| width: 200px; |
| line-height: 100px; |
| text-align:center; |
| margin: 100px; |
| } |
| </style> |
| <body> |
| <p>Haha</p > |
| <div class="container"> |
| <p>Hehe</p > |
| </div> |
| </body> |
复制
清除内部浮动
正常情况下,由于浮动元素的存在.par是不会有高度的,可以给他加上overflow: hidden;变为BFC,就会计算浮动元素的高度了
| <style> |
| .par { |
| border: 5px solid #fcc; |
| width: 300px; |
| overflow: hidden; |
| } |
| |
| .child { |
| border: 5px solid #f66; |
| width:100px; |
| height: 100px; |
| float: left; |
| } |
| </style> |
| <body> |
| <div class="par"> |
| <div class="child"></div> |
| <div class="child"></div> |
| </div> |
| </body> |
复制
自适应多栏布局
正常情况下.aside会浮动并且压在.main上,可以根据BFC的区域不会与浮动盒子重叠的特性,把.main变为BFC,这样.main就实现了宽带自适应了,并且实现左右两栏布局了。
| <style> |
| body { |
| width: 300px; |
| position: relative; |
| } |
| |
| .aside { |
| width: 100px; |
| height: 150px; |
| float: left; |
| background: #f66; |
| } |
| |
| .main { |
| height: 200px; |
| background: #fcc; |
| overflow: hidden; |
| } |
| </style> |
| <body> |
| <div class="aside"></div> |
| <div class="main"></div> |
| </body> |
复制