0

How do I align an h1 and h2 both vertically and horizontally, while keeping the height 100% of the viewport?

I've added align-items: center; justify-content: center; to the container and text-align: center; vertical-align: center; to the header class. Adding display: block; to either does nothing.

Expected:

How I want it to look

Actual:

How mine looks

What's going one exactly? Is it the navbar?

#welcome-section {
  height: 100vh;
  align-items: center;
  justify-content: center;
}

.welcome-header {
  text-align: center;
  vertical-align: center;
}
<div id="welcome-section">
  <h1 class="welcome-header">Namaste, Kevin here.</h1>
  <h2 class="welcome-header">And I'm a front-end developer</h2>
</div>
Community
  • 1
  • 1
Kaiwen Lin
  • 15
  • 5
  • You could look into this similar question https://stackoverflow.com/questions/79461/vertical-alignment-of-elements-in-a-div – Nicolas Aug 30 '18 at 20:25
  • the `align-items` and `justify-content` properties are for elements with `display: flex;`. Have you tried adding `display: flex;` to your `#welcome-section`? You may also need `flex-direction: column` – zgood Aug 30 '18 at 20:34

2 Answers2

0

If you use flex alignement properties, then the flex display is required.

#welcome-section {
  height: 100vh;
  display:flex;/*this is  what was missing */
  flex-flow:column;/*this is  what was missing too*/
  align-items: center;
  justify-content: center;
}

https://codepen.io/gc-nomade/pen/MqJgVG

body {
  margin:0;
}

#welcome-section {
  height: 100vh;
  align-items: center;
  justify-content: center;
  display: flex;       /*this is  what was missing */
  flex-flow: column;  /*this is  what was missing too*/
}

.welcome-header {
  text-align: center;
  /*vertical-align: center; useless*/
}
<div id="welcome-section">
  <h1 class="welcome-header">Namaste, Kevin here.</h1>
  <h2 class="welcome-header">And I'm a front-end developer</h2>
</div>
Temani Afif
  • 180,975
  • 14
  • 166
  • 216
G-Cyrillus
  • 85,910
  • 13
  • 85
  • 110
0

Set your parent class to relative

#welcome-section {
  height: 100vh;
  align-items: center;
  justify-content: center;
  position:relative;
}

Then wrap your welcome-header with both your h1 h2 tags And make it absolute and center it:

.welcome-header {
  text-align: center;
  vertical-align: center;
  position:absolute;
  left:0;
  right:0;
  top:50%;
  margin-bottom:20px;
}


<div id="welcome-section">
  <div class="welcome-header">
    <h1>Namaste, Kevin here.</h1>
    <h2>And I'm a front-end developer</h2>
  </div>
</div>

Codepen link

Rodolfo R
  • 197
  • 1
  • 2
  • 13