CSS – Place elements in the center of the screen

This is to place html elements in the center. In this example, it uses absolute/relative position and transform (translate) in order to place properly.
Please note that I have learned this from the udemy course by Jonas Schmedtmann.


Please note that there are two texts here – primary, secondary. They are in same h1 but in different span in order to manage it easily.

Example Code

<!DOCTYPE html>
<html lang="en">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900" rel="stylesheet">

        <link rel="stylesheet" href="css/icon-font.css">
        <link rel="stylesheet" href="css/style.css">
        <link rel="shortcut icon" type="image/png" href="img/favicon.png">
        <!-- <title>Natours | Exciting tours for adventurous people</title> -->
        <title>clip-path and linear-gradient</title>
        <header class="header">
            <div class="text-box">
                <h1 class="heading-primary">
                    <span class="heading-primary-main">Primary</span>
                    <span class="heading-primary-secondary">Secondary</span>

As you can see the above code, this is nested in a couple of levels. div with class text-box is the place where I will use absolute position in the css code. But you have to provide a reference point of that position. That’s where header element will include so that the child will always be in the center of the parent – header – and parent will be placed for the responsive view.

Another thing to note is top, left which specifies the left, top position of the child element. For example, if you just specify top 50%, left: 50%, you will see the text is not located in the center because the positions actually mean the top left point of the element. That’s why we need to transform the text accordingly in order to place it in the center. You can use transform/translate property in order to move the child element.

.header {
  height: 95vh;
  background-image: linear-gradient(
    to right, 
  background-size: cover;
  background-position: top;
  /* this is for logo-box */
  position: relative;

  /* Trapezoid */
  clip-path: polygon(0 0, 100% 0, 100% 90%, 0 100%);
  /* Triangle */
  /* clip-path: polygon(0 0, 100% 50%, 0 100%) */
  /* you can use pixel or vh */
  /* clip-path: polygon(0 0, 100% 0, 100% 75vh, 0 100%); */

.text-box {
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translate(-50%, -50%);

.heading-primary {
  color: #fff;
  text-transform: uppercase;


.heading-primary-main {
  display: block;
  font-size: 60px;
  font-weight: 400;
  letter-spacing: 35px;

.heading-primary-secondary {
  display: block;
  font-size: 20px;
  font-weight: 700;
  letter-spacing: 17.4px;