html - 小于浏览器高度时垂直居中 div (Bootstrap)

标签 html css bootstrap-4

我使用的是 CSS bootstrap 4,容器内每行有多个列。根据屏幕尺寸,这些列可以堆叠在一起并使容器更高,有时会超出屏幕上可以显示的范围并需要滚动。我似乎无法找到一种方法来满足这两个条件:

  • 如果容器比浏览器窗口高度短,则将容器置于屏幕中间
  • 如果容器高于浏览器窗口高度,请不要将容器居中(这样它就不会离开屏幕)

我有代码让下面的容器居中,但是当文本行数变得比屏幕高时,它会因为 .centered 而离开屏幕,并且不能像普通页面那样滚动

这是我的 HTML:

<div class="container centered" style="width: 100%">
    <div class="row justify-content-center">
            <div class="col-8" id="main">
                Text<br>
                Text<br>
                Text<br>
                <!-- Any number of more lines may be added here -->
            </div>
    </div>
</div>

还有我的 CSS:

html,
body {
  width: 100%;
}

body {
  display: -ms-flexbox;
  display: flex;
  -ms-flex-align: center;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: rgb(0, 0, 0);
}

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#main {
  background-color: rgb(30,29,38.3);
  border-radius: 6px;
  box-shadow: 0 0 30px rgb(25, 25, 35);
}

最佳答案

<body class="d-flex justify-content-center align-items-center"></body>

(或)

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

关于html - 小于浏览器高度时垂直居中 div (Bootstrap),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59123704/

相关文章:

html - 设置具有 2 个级别的父级的全宽 div?

javascript - 加载后动态添加 facebook 之类的按钮

css - 模拟器检查 outlook 中的元素

html - col-xl-12 不是 div 父亲的 100%

html - 使用 Bootstrap 4 将标签元素内的图标定位到右侧

html - 在列表标签​​中将光盘居中对齐

CSS div 固定定位

html - 触摸屏设备支持 onmousedown 和 onmouseup 吗?

html - 自动高度 div 不工作

html - 如何仅使用 CSS 将图像定位到进度条的值