本文来自于个人前端基础知识积累项目《菜鸟进阶》
水平居中
- 行内元素使用text-align:center 实现行内元素水平居中
- 块级元素,设置margin:0 auto;
.parent {
width: -webkit-fit-content;
width: -moz-fit-content;
width: fit-content;
margin: 0 auto;
}
- flex布局 display:flex; justify-content:center;
// flex 2012年版本写法
.parent {
display: flex;
flex-direction: row;
justify-content: center;
}
// flex 2009年版本写法
.parent {
display: box;
box-orient: horizontal;
box-pack: center;
}
- transform属性
position:absolute;
left:50%;
transform;translate(-50%,0)
.child {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
- 绝对定位 position:absolute;width:200px;left:50%;margin-left:-100px;(需要固定宽度)
.child {
position: absolute;
left: 50%;
width: 200px; // 假定宽度为200px
margin-left: -100px; // 负值的绝对值为宽度的一半
}
- 绝对定位 position:absolute;left:0;right:0;margin:0 auto;(需要固定宽度)
.child {
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
width: 200px; // 假定宽度为200px
}
垂直居中
- 单行文本设置line-height:父元素高度
- 行内块级元素 display:inline-block、vertical-align:middle和伪元素让内容居中
.parent::after .son{
display:inline-block;
vertical-align:middle;
}
.parent::after{
content:'';
height:100%;
}
- transform 设置父元素相对定位(position:relative),子元素如下:
.son {
position:absolute;
top:50%;
transform:(-50%,-50%);
}
- 设置父元素相对定位 position:relative,子元素CSS样式如下:
.son{
position:absolute;
height:200px;
top:0;
bottom:0;
margin:auto 0;
}
- 设置父元素相对定位 position:relative,子元素CSS样式如下:
.son {
position:absolute;
height:200px;
top:0;
bottom:0;
margin:auto 0;
}
- 使用vertical-align属性并且配合使用display:table和display:table-cell来让内容块居中
.parent {
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
- 使用flex布局的方式,可以轻松实现垂直居中,即使子元素中存在浮动元素也同样适用
// flex 2012年版本写法
.parent {
display: flex;
align-items: center;
}
// flex 2009年版本写法
.parent {
display: box;
box-orient: vertical;
box-pack: center;
}
水平垂直居中
- 使用flex布局的方式同样可以轻松实现水平垂直居中
// flex 2012年版本写法
.parent {
display: flex;
justify-content: center;
align-items: center;
}
// flex 2009年版本写法
.parent {
display: box;
box-pack: center;
box-align: center;
}
- 使用绝对定位的方式,再配合CSS3新增的transform属性
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
- 使用绝对定位的方式,再配合使用负值的margin-top和负值的margin-left(此方法需要同时固定宽度和高度)
.child {
position: absolute;
left: 50%;
top: 50%;
margin-top: -50px; // 负值的绝对值为高度的一半
margin-left: -100px; // 负值的绝对值为宽度的一半
width: 200px; // 假定宽度为200px
height: 100px; // 假定高度为100px
}