.parent{
text-align:center
}
.son {
margin: 0 auto;
}
**子元素含 float **
.parent{
width:fit-content;
margin:0 auto;
}
.son {
float: left;
}
flex弹性盒子
.parent{
display:flex;
justify-content:center;
}
绝对定位
transform
.son {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
left:50%
.son {
position: absolute;
width: 宽度;
left: 50%;
margin-left: -0.5*宽度
}
left/right :0
.son {
position: absolute;
width: 宽度;
left: 0;
right: 0;
margin: 0 auto;
}
子元素行高等于父元素的高度,且子元素只有单行文本
.parent {
height: 高度;
}
.son {
line-height: 高度;
}
行内块元素
.parent::after, .son{
display:inline-block;
vertical-align:middle;
}
.parent::after{
content:'';
height:100%;
}
table
优点
元素高度可以动态改变, 不需再CSS中定义, 如果父元素没有足够空间时, 该元素内容也不会被截断。
缺点
IE6~7, 甚至IE8 beta中无效。
.parent {
display: table;
}
.son {
display: table-cell;
vertical-align: middle;
}
flex弹性盒子
优点
缺点
.parent {
display: flex;
align-items: center;
}
绝对定位 IE8不支持, 属性需要追加浏览器厂商前缀, 可能干扰其他 transform 效果, 某些情形下会出现文本或元素边界渲染模糊的现象。
.son {
position: absolute;
top: 50%;
transform: translate( 0, -50%);
}
top:50% 父元素空间不够时, 子元素可能不可见(当浏览器窗口缩小时,滚动条不出现时).如果子元素设置了overflow:auto, 则高度不够时, 会出现滚动条。
.son {
position: absolute;
top: 50%;
height: 高度;
margin-top: -0.5高度;
}
top/bottom:0;
没有足够空间时, 子元素会被截断, 但不会有滚动条。
.son {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
}