如何让div在body可视区域水平垂直居中?

这里不是说div里面的内容,水平垂直居中。
而是div这个容器在浏览器可视区域内水平垂直居中,并且div的高度宽度自适应,也就是说不能写死div的宽度高度,内容自适应。
以前有一种写法是绝对定位, 还要设置宽度高度,CSS3现在不是有弹性布局和网格布局吗,不知道能不能快速实现。

阅读 2.9k
3 个回答
  1. 父容器使用 position: fixed,上下左右都是 0,填满视窗
  2. 然后 display:flex; justify-content: center; align-items: center,把子容器居中
  3. 最后字容器的宽高根据内容来调整。

大体上:

.parent {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}
.center {
  width: fit-content;
  height: fit-content;
}

方法一

使用flex布局

<body>
  <div class="container">
    <div class="content">这里是内容</div>
  </div>
</body>    
html,
body {
  height: 100%;
  margin: 0;
}

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

.content {
  width: auto;
  max-width: 90%;
  padding: 20px;
}

方法二

使用定位

<body>
  <div class="container">
    <div class="content">这里是内容</div>
  </div>
</body>    
html,
body {
   height: 100%;
   margin: 0;
}

.container {
   position: relative;
   height: 100%;
}

.content {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
   
   max-width: 480px;
   padding: 20px;
}

你说的那种方式可能是这样,以前需要写具体的宽高,现在可以写成fit-content

.box{
    position: absolute;
    inset: 0;
    margin: auto;
    width: fit-content;
    height: fit-content;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题