行内元素水平居中:text-align: center
块级元素水平居中:margin: 0 auto
<!-- 水平垂直居中 -->
<style>
.parent {
width: 600px;
height: 300px;
border: 1px solid red;
position: relative;
}
.child {
width: 300px;
height: 150px;
border: 1px solid green;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
</style>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
<!--兄弟元素水平垂直居中 -->
<style>
.parent {
width: 600px;
height: 300px;
border: 1px solid red;
}
.child {
width: 300px;
height: 150px;
border: 1px solid green;
line-height: 150px;
display: inline-block;
vertical-align: middle;
}
.brother {
height: 100%;
width: 2px;
background: pink;
display: inline-block;
vertical-align: middle;
}
</style>
<body>
<div class="parent">
<div class="child"></div>
<div class="brother"></div>
</div>
</body>
<!--元素水平垂直居中 -->
<!-- translate()函数是css3的新特性.在不知道自身宽高的情况下,可以利用它来进行水平垂直居中.。
当使用:top: 50%;left: 50%;, 是以左上角为原点,故不处于中心位置
translate(-50%,-50%) 作用是,往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置。 -->
<style>
.parent {
width: 600px;
height: 300px;
border: 1px solid red;
position: relative;
}
.child {
width: 300px;
height: 150px;
border: 1px solid green;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
</style>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>