3

I want to make <h1> centered.

Problem: When I center the text horizontally, I can't center it vertically, and if I center it vertically, then I can't do it horizontally .

My code :

h1 {
  font-weight: 400;
  text-transform: uppercase;
  font-size: 28px;
}

.main-text {
  text-align: center;
}
<header>
  <div class="main-text">
    <h1>This is Centered Text.</h1>
  </div>
</header>

What I Tried : Here are the some CSS that I tried .

.main-text {
        text-align: center;
        vertical-align: middle;   
    }

The below code works but then the text isn't responsive .

.main-text {
    position: absolute;
    top: 30%;
    left: 30%;

}

How I want it to look: How I want it to look

j08691
  • 204,283
  • 31
  • 260
  • 272
Arsalan Khattak
  • 768
  • 2
  • 8
  • 16

2 Answers2

7

Solution 1: Use CSS 2D transforms

You can use the good old trick of positioning the <h1> element absolutely, use 50% for left and top cardinal coordinates, and then translate it to the top and left by half of its own dimensions. Note that you must declare an explicit height on the parent, otherwise the trick will not work.

h1 {
    font-weight: 400;
    text-transform: uppercase;
    font-size: 28px;
}

.main-text {
    position: relative;
    width: 100%;
    
    /* You need to define an explicit height! */
    height: 100vh;
}

.main-text h1 {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  text-align: center;
}
<header>
<div class="main-text">
  <h1>This is Centered Text.</h1>
</div>
</header>

Solution 2: Use flexbox

Since flexbox is very widely supported, you can also use it. This can be done by simply declaring the following rules on the parent wrapping element:

.main-text {
  display: flex;
  align-items: center;
  justify-content: center;
}

h1 {
    font-weight: 400;
    text-transform: uppercase;
    font-size: 28px;
}

.main-text {
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    width: 100%;
    
    /* You need to define an explicit height! */
    height: 100vh;
}
<header>
<div class="main-text">
  <h1>This is Centered Text.</h1>
</div>
</header>
Terry
  • 63,248
  • 15
  • 96
  • 118
2

body{
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  
  width: 100%;
  min-height: 100vh;
}
  
<div class="main-text">
  <h1>This is Centered Text.</h1>
</div>

If you can use the flex, try to use the flex.

If you want to get more information about the flex,

visit here https://codepen.io/enxaneta/pen/adLPwv?q=flex&limit=all&type=type-pens

kyun
  • 9,710
  • 9
  • 31
  • 66