居中
块元素水平居中
.parent {
width: 100%;
}
.child {
width: 600px;
height: 50px;
margin: 0 auto;
}
行内元素水平居中
.parent {
text-align: center;
}
模拟表格 实现水平居中
display:table (<table>) | table-row (<tr>) | table-cell (<td>)
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}
垂直水平居中,内容宽高固定
.child {
width: 100px;
height: 150px;
position: absolute;
top: 50%;
margin-top: -75px;
left: 50%;
margin-left: -50px;
}
垂直水平居中,内容宽高不固定
.child {
width: 100px;
height: 150px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
垂直水平居中,内容宽高不固定。
transform属性,CSS3变形,
translate(-50%, -50%) 水平向左移动自身宽度的50%,垂直向上移动自身宽度的50%
.parent {
position: relative;
}
.child {
width: 100px;
height: 150px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
CSS3新特性 移动端水平垂直居中
Flex布局 IE10+
设为Flex布局后,子元素的float、clear、vertical-align属性会失效
.parent {
display: flex;
justify-content: center;
align-items: center;
}
BFC是什么?
BFC: Block Formattig Context 块级格式化上下文
IFC: Inline Formatting Context 行级格式化上下文
BFC用于页面渲染,决定盒子的布局,浮动相互影响范围的一个区域。BFC之间不会相互影响。
可以解决问题:
- 浮动元素的父元素高度坍塌
- 两栏自适应布局
- 外边距垂直方向重合
创建BFC的方式:
- position: absolute | fixed;
- display: inline-block | table-cell | table-caption;
- overflow: hidden | auto;
盒模型有哪两种模式?
- 标准模式
-
怪异模式(兼容模式)
盒子模式.png
文档头部的DOCTYPE,防止浏览器渲染文档时用怪异模式。
HTML5的头部
<!DOCTYPE html>