body的高度为0怎么设置水平垂直居中?

如图

clipboard.png

clipboard.png

clipboard.png

body和父盒子高度全部都是0

但是我是设置了

html,body { height:100%;}

但是应该是没有生效?
然后导致整个页面居中也有问题

clipboard.png

居中的css代码

.login-container {
  position: relative;
  width: 100%;
  height: 100%;
}
  .login-form {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, 50%); /*本来是(-50%, -50%) 但是这样直接不可见了*/
    width: auto;
    height: auto;
  }
阅读 5.4k
5 个回答

body和父元素高度为0,那么一般的定位就不起作用了,只能使用fixed,相对于浏览器定位

.box{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.login-container {
    position: relative;
    width: 100%;
    height: 100vh;
}

.login-form {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    height: 200px;
    margin-top: -100px;
    margin-left: -100px; 
}

建议你可以看下这篇文章:CSS实现水平垂直居中的10种方式

方法很多
建议用flex,简单有效
display:flex;
justify-content:center;
align-items:center

可以使用fixed定位。

.container {
  position: fixed;
  top: 0; right: 0; bottom: 0; left: 0;
  text-align: center;
  white-space: nowrap;
}
.container:after {
  content: "";
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
.login-container {
  display: inline-block;
  vertical-align: middle;
  text-align: left;
  white-space: normal;
}

如果是支持flex布局的话:

.container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
}

*{

        margin:0;
        padding:0;
    }
    html{
        height:100%;
    }
    body{
        height:100%;
        display: flex;
        flex-direction: column;
        justify-content:space-between;
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题