无法在 Flexbox 中将 div 居中

嗨,所以我只需要一些帮助flexbox,我查看了其他人,甚至复制了那里的代码进行测试,但由于某种原因它不起作用。我正在尝试让div内容在网站的顶部中心对齐。这是我当前的代码,


索引.html

<div class="header"> 

  <div class="headerContent">

    <h1>TEST<h1>

  </div>

</div

样式.css

html { 

  display: flex;

}

.header {

  display: flex;

  align-items: center;

  justify-content: center;

  flex-direction: column;

}

 .headerContent {

    background-color: #2C374C; 

    width: 100%;

   justify-content: center;

}


芜湖不芜
浏览 125回答 3
3回答

九州编程

看来你正在做正确的事情,但在错误的元素上。当它是子容器时,您将.headerid 视为父容器。在这种情况下,容器层次结构如下html-> header->.headerContent因此,要居中,header您需要对其父级采取行动。将其想象为父母向其孩子发出命令(字面意思)。html {&nbsp;&nbsp; display: flex;&nbsp; justify-content: center;}通过这样做,父组件正在证明其内容(子组件)我还建议不要使用 html 创建另一个 div 容器作为标头 div 的父容器,如下所示.headerContainer {&nbsp;&nbsp; display: flex;&nbsp; justify-content: center;&nbsp; background-color: red}.header {&nbsp; display: flex;}&nbsp;.headerContent {&nbsp; &nbsp; background-color: #2C374C;&nbsp;&nbsp; &nbsp; width: 100%;}&nbsp; &nbsp; <div class="headerContainer">&nbsp; &nbsp; &nbsp; <div class="header">&nbsp;&nbsp; <div class="headerContent">&nbsp; &nbsp; <h1>TEST<h1>&nbsp; </div>&nbsp;</div>&nbsp; &nbsp; </div>

子衿沉夜

我想就像这样.header {&nbsp; width: 100%;}.headerContent {&nbsp; background-color: #2c374c;&nbsp; width: 100%;&nbsp; display: flex;&nbsp; justify-content: center;&nbsp; align-items: center;&nbsp; flex-direction: column;}<html>&nbsp; <link rel="stylesheet" href="style.css" />&nbsp; <div class="header">&nbsp; &nbsp; <div class="headerContent">&nbsp; &nbsp; &nbsp; <h1>Test</h1>&nbsp; &nbsp; </div>&nbsp; </div></html>

眼眸繁星

当您使用flex-direction: column;, 来水平居中时,请使用align-items: center;而不是justify-content: center;您还设置了一个height属性。例子:.header{&nbsp; display: flex;&nbsp; height: 300px;&nbsp; justify-content: center;&nbsp; align-items: center;&nbsp;&nbsp;&nbsp; background: red}<header class="header">&nbsp; <div>centered</div></header>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5