0

So I am just fiddling for some curiosity on jsFiddle. When I apply style on below HTML:

<p>Hello World</p>

Styles:

p {
  position:relative;
  top: 50%;
  left: 50%;
}

The Hello World comes to the center horizontally but not vertically.

But , when I change the position from relative to absolute, the element aligns horizontally and vertically as well.

As I understand positioning, top: 50% should change the top of a block element.

Anything I am missing here (conceptually or otherwise)?

p {
  position:relative;
  top: 50%;
  left: 50%;

}
<p>Hello World</p>
scooterlord
  • 15,124
  • 11
  • 49
  • 68
PiyushD
  • 61
  • 7
  • 1
    Relative positioning works relative to parrent, but absolute works comparing to closest parent with position relative / absoute / fixed or if there is not, it possitions according to window height. – Andris Dec 05 '19 at 09:57
  • @Andris *Relative positioning works relative to parrent* --> it works relatively to the element position, not the parent – Temani Afif Dec 05 '19 at 10:04
  • Well yes, but same time positioning is compared against parent. 'p' won't be 50% from top if parent height isn't 100% from window height in this example. This case 'relative' to work body should have css: {height: 100vh} – Andris Dec 05 '19 at 10:08
  • Answered!....... – Ahmed Ali Dec 05 '19 at 10:09
  • @Andris , as far as I know relative is "relative to its original position in the flow" , didn't know about this parent stuff . Is there a link where I can study it properly ? Thanks . – PiyushD Dec 05 '19 at 10:14
  • I don't know actually. I learned this while working on projects. But this is all, what is needed in this scenario. – Andris Dec 05 '19 at 10:16

2 Answers2

1

For position relative, it parent should have an static height. As I assign height to body it worked!.

p{
  position:relative ;
  top : 50%;
  left : 50%;
}
body{
  height:100vh;
}
<p>Hello World</p>
Andris
  • 3,895
  • 2
  • 24
  • 27
Ahmed Ali
  • 1,908
  • 14
  • 28
  • 1
    now thats solid ! This height issue is not in absolute position ? – PiyushD Dec 05 '19 at 10:10
  • in absolute position it looks if one of parents has relative / absolute / fixed positions. If not, than it looks on windows height and positions accordingly. – Andris Dec 05 '19 at 10:11
-1

I have this kind of problem lot of time and to use position absolute some times are not a good idea so I have always used flex css.

body{
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
}

for p no css is required.

Deep
  • 64
  • 6
  • 1
    yeah @Deep , I know the flex box method , but I am trying to solidify my understanding of core concepts. thanks for your answer thyough – PiyushD Dec 05 '19 at 10:06