1.不知道自己高度和父容器高度的情况下, 利用定位:
.parentElement{
position: relative;
height: inherit;//继承父节点的长宽
width: inherit;
}
.childElement{
position: absolute;
top: 50%;
transform: translateY(-50%) translateX(-50%);
left: 50%;
}
<div style="width:200px;heigth:200px">
<div class="parentElement">
<div class="childElement">login</div>
</div>
</div>
复制代码
2.若父容器下只有一个元素,且父元素设置了高度,则只需要使用相对定位即可
.parentElement{
height: 200px;
width: 200px;
}
.childElement {
position: relative;
top: 50%;
left: 50%;
display: table;
transform: translateY(-50%) translateX(-50%);
}
<div class="parentElement">
<div class="childElement">login</div>
</div>
复制代码
使用table
.tablep{
display: table-cell;
vertical-align:middle;
text-align: center;
width: 100px;
height: 100px;
}
<div class="tablep">
<div>login</div>
</div>
复制代码
3.不考虑兼容老式浏览器的话,用Flex布局简单直观一劳永逸: 模拟弹出窗
<style>
.parent {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
height: 100%;
z-index: 99;
display: flex;
align-items: center;
justify-content: center;
}
.child {
background-color: #fff;
}
</style>
<div class="parent">
<div class="child">login</div>
</div>
复制代码