前端常用居中方式
整理了一些前端常用的居中方法,有错误的地方请大家多多指教。
水平居中
transform(css3)
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
flex布局(css3)
.parent {
display: flex;
justify-content: center;
}
居中的元素为内联元素
.parent {
text-align: center;
}
居中的元素为块级元素
方法一:设置margin
.child {
margin: 0 auto;
}
方法二:元素修改为inline-block
.parent {
text-align: center;
}
.child {
display: inline-block;
}
居中元素为块级元素且知道宽度
方法一:
.child {
position: relative;
width:100px;
left: 50%;
margin-left: -50px;
}
方法二:
.parent {
position: relative;
}
.child {
position: absolute;
width:100px;
left: 50%;
margin-left: -50px;
}
垂直居中
transform(css3)
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
flex布局(css3)
.parent {
display: flex;
align-items: center;
}
子元素为内联元素
.parent{
line-height: 100px;
height: 100px;
}
居中元素为块级元素且高度固定
方法一:
.parent {
position: relative;
}
.child {
height: 100px;
position: absolute;
top: 50%;
margin-top: -50px;
}
方法二:
.child {
position: relative;
top: 50%;
height: 100px;
margin-top: -50px;
}