水平垂直居中的几种方法
先水平再垂直
通过设置margin: 0 auto实现水平居中
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto;
}
在这之后,我们先要设置div元素的祖先元素html和body的高度为100%,再通过定位使其向下移动,最后设置margin-top属性垂直居中
html,body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto; /*水平居中*/
position: relative;
top: 50%; /*偏移*/
margin-top: -150px;
}
flex 布局
html,body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
align-items: center; /*定义body的元素垂直居中*/
justify-content: center; /*定义body的里的元素水平居中*/
}
.content {
width: 300px;
height: 300px;
background: orange;
}
只需要设置父元素即可
绝对定位 + transform
.box {
position: relative;
}
.item {
position: absolute;
left: 50%;
right: 50%;
transform: translate(-50%, -50%);
}
这与第一个方法差不多
行内元素
于行内元素来说,垂直居中可以将line-height的值设为元素高度。而水平居中只需要设置父元素text-align属性为center。
如果要居中的不是文本,对于设置了display为inline-block的元素来说,也是可以做到的。inline-block身负行内元素与块级元素的特性
.box {
width: 300px;
height: 400px;
border: 1px red solid;
text-align: center;
}
.item {
height: 40px;
display: inline;
line-height: 400px;
border: 1px solid green;
}