【问题标题】:How to vertically center a div on the available screen height?如何在可用屏幕高度上垂直居中 div?
【发布时间】:2021-02-27 12:18:35
【问题描述】:

我知道如何在屏幕上或使用 flexbox 的父容器中垂直居中 div。但是,我不能在剩余的屏幕高度上垂直居中 div。

基本上:

  • 我有一个带有页眉的页面,在一个包含一些内容的 div 下方。内容应以剩余高度垂直居中。
  • height:100vh 提供给父包装器时,div 居中,但父div 变得太长并溢出视口。因此对中不正确。给父母一个height:100%时,它没有效果。

如何解决这个问题?这是代码和沙箱:

html:

export default function App() {
  return (
    <div className="App">
      <header>
        <h1>Header</h1>
      </header>
      <div className="content-wrapper">
        <div className="content">
          <h3>content</h3>
        </div>
      </div>
    </div>
  );
}

CSS:

body {
  margin: 0;
  background: black;
  height: 100vh;
}

.App {
  font-family: sans-serif;
  text-align: center;
}

header {
  padding: 24px;
  color: white;
  border: 1px solid white;
}

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

.content {
  border: 1px solid orange;
  padding: 24px;
  width: 100%;
}

沙盒:https://codesandbox.io/s/happy-wright-c85gi?file=/src/styles.css

感谢您的帮助!

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    内容包装器必须填满所有剩余的屏幕。所以:

    .App{
        display: flex;
        flex-direction: column;
        height: 100vh;
     }
    
    .content-wrapper
    {
        flex: 1;
        justify-content: center;
        align-items: center;
    }
    

    【讨论】:

      【解决方案2】:
      /* MIDDLE AND CENTER ELEMENT */
      .middle-center {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
      
      /* IN YOUR CODE */
      .content {
        border: 1px solid orange;
        padding: 24px;
        width: 100%;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
      

      【讨论】:

      • 感谢您的帮助。我已经验证了另一个解决方案,因为它更简单。
      猜你喜欢
      • 2014-05-26
      • 2017-11-05
      • 2013-06-15
      • 2010-09-08
      • 1970-01-01
      • 2013-06-24
      • 1970-01-01
      • 2018-01-20
      • 2014-05-27
      相关资源
      最近更新 更多