0

Hi so I just need some help on flexbox, ive looked at other people and even copied there code to test but for some reason it isnt working. I'm trying to get a div with content aligned in the center top of a website. Here is my current code,

index.html

<div class="header"> 
  <div class="headerContent">
    <h1>TEST<h1>
  </div>
</div

style.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;
}
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41

3 Answers3

0

when you use flex-direction: column;, to center horizontally use align-items: center; instead of justify-content: center;

You also have set a height property.

Example:

.header{
  display: flex;
  height: 300px;
  justify-content: center;
  align-items: center;
  
  background: red
}
<header class="header">
  <div>centered</div>
</header>
0

it seems you are doing the right thing but on the wrong element. Your are treating the .header id as the parent container when it is the child.

In this case the container hierarchy is the following html -> header -> .headerContent

So to center header you need to act on its parent. Imagine it as a parent giving order to its child (literally).

html { 
  display: flex;
  justify-content: center;
}

by doing this the parent component is justifying its content (children)

I would also recommend instead of using html to create another div container to be the parent of your header div like so

.headerContainer { 
  display: flex;
  justify-content: center;
  background-color: red
}
.header {
  display: flex;
}
 .headerContent {
    background-color: #2C374C; 
    width: 100%;
}
    <div class="headerContainer">
      <div class="header"> 
  <div class="headerContent">
    <h1>TEST<h1>
  </div>
 </div>
    </div>
0

I think just like this

.header {
  width: 100%;
}
.headerContent {
  background-color: #2c374c;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
<html>
  <link rel="stylesheet" href="style.css" />
  <div class="header">
    <div class="headerContent">
      <h1>Test</h1>
    </div>
  </div>
</html>
Alendra
  • 21
  • 2