[CSS] How to Center Your Text

Have you ever got a trouble with using an absolute position property? Yes many developers and designers have been struggling with making their text on centre of the page. 

In this blog, I will explain easy to make centre your elements

 

 
[HTML]
1
2
3
4
5
6
7
8
9
10
11
12
13
    <body>
        <header class="header">
            <div class="logo-box">
                <img src="img/logo-white.png" alt="Logo" class="logo">
            </div>
            <div class="text-box">
                <h1 class="heading-primary">
                    <span class="heading-primary-main">Outdoors</span>
                    <span class="heading-primary-sub">is where life happends</span>
                </h1>
            </div>
        </header>
    </body>
cs

 

[CSS]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.header {
    height: 95vh;
    background-image: linear-gradient(
        to right bottom,
        rgba(126, 213, 111, 0.8),
        rgba(40, 180,131, 0.8)),
    url(../img/hero.jpg);
    background-size: cover;
    background-position: top;
    position: relative;
 
    clip-path: polygon(0 0, 100% 0,100% 75vh, 0 100%);
}
 
.text-box {
    position: absolute;
    top: 50%;
    left: 50%;
}
cs

 

 

As you can see the screen shot, the child element which is set by absolute position is started the 50% of parent element!

 

So you should GIVE transform property with translate(x,y) value, Therefore, the translate value revise the starting point of child elements!

 
1
2
3
4
5
6
.text-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
cs

Leave a Comment

en_USEnglish