水平居中
text-align: center
对于行内和类行内元素,如链接和文本,可以使用
.element {
text-align: center;
}
块级元素可使用display: inline-block
.parent {
text-align: center;
}
.child {
display: inline-block;
}
margin和width
对于块级元素,已经对这个元素设置了一定的宽度width时,可以将margin-left和margin-right设为auto,如果没有设置width,块级元素的宽度会被拉伸为父级容器的宽度。
.element {
width: 200px;
margin: 0 auto;
}
使用flex
.parent {
display: flex;
justify-content: center;
}
垂直居中
line-height
如果父元素中只有单行文本,可以将子元素的line-height设置为与父元素的高度相同
.parent {
height: 100px;
}
.child-text {
line-height: 100px;
white-space: nowrap;
}
padding-top 和 padding-bottom
如果父元素中只有单行元素,而且父元素没有设置固定的高度,也就是说父元素的高度是由它的内容撑开的,可以将父元素的padding-top和padding-bottom设置为相同的值
.parent {
padding-top: 30px;
padding-bottom: 30px;
}
使用绝对定位 + margin-top,margin-left
使用position:absolute,top和left设为50%,margin-left/margin-top分别设置为 -宽高的一半。这种方式的不足之处是需要固定元素的宽高
.parent {
position: relative;
}
.child {
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
使用绝对定位 + transform的translate函数
这种方法不需要已知元素的宽高,也可以用translateX,translateY
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
使用table-cell + vertical-align
设置父元素为display:table-cell,但父元素有浮动和绝对定位会使这种方法失效
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
使用::before伪元素加vertical-align
.parent::before {
content: "";
display: inline-block;
heihgt: 100%;
vertical-align: middle;
}
.child {
display: inline-block;
vertical-align: middle;
}
使用flex
设置父元素为display: flex, 用justify-content水平居中,用align-items垂直居中
.parent {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}













网友评论