-1

I learnt a new (new to me) way of centering divs from an online resource. I can not get hold of the author, so please explain what exactly is happening here.

<header class="header">
        <div class="header-box">
            <h1>
                Lorem Ipsum <br>
                Dolor sit amet
            </h1>
        </div>
    </header>

.header {
    position: relative;
    height: 100vh;
    background-image: linear-gradient(
        to right bottom, 
        rgba(17, 63, 112), 
        rgba(253, 135, 31));
    background-position: top;
}

.header-box {
    position: absolute;
    top: 50%;  /*This and next line*/
    left: 50%; 
    transform: translate(-50%, -50%); /*and this*/
}

h1 {
  text-align: center;
}

How exactly the Transform property is aligning the div in center perfectly when the position property pushed it away?

https://jsfiddle.net/ux1r3eb0/

DBS
  • 9,110
  • 4
  • 35
  • 53
Bluebug
  • 294
  • 4
  • 13

2 Answers2

1

I'll describe this in the context of horizontal alignment, but exactly the same principles apply to vertical alignment:

The absolute position moves the element's left side to the centre of the screen, then the transform moves the element's centre left by half it's width, which lines up the centre of the element with the centre of the container.

Visual example (I'm only showing the horizontal movement, to make it easier to understand):

.container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/AAAZ4gk3AAAACklEQVR4XmNgAAAAAgAB3p6PvwAAAABJRU5ErkJggg==');
  background-position: center;
  background-size: 1px 100%;
  background-repeat: no-repeat;
}

.content {
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;
  border: 1px solid #F00;
  animation-name: demo;
  animation-duration: 8s;
  animation-fill-mode: forwards;
}

@keyframes demo {
  0% {
    left: 0%;
    transform: translate(0%, -50%);
  }
  50% {
    left: 50%;
    transform: translate(0%, -50%);
  }
  100% {
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
<div class="container">
  <div class="content"></div>
</div>
DBS
  • 9,110
  • 4
  • 35
  • 53
0

The top and left property pushed away the .header-box from the top and left side of .header. 50% value means 50 percent of height and width of .header

while the translate(-50%, -50%) makes the .header-box to pull back itself by half of the size of itself.

When you use percentage in top, left, right, bottom property, it uses the size of closest positioned ancestor element, while the transform uses the size of itself.