html - Why is translateY(-50%) needed to center an element which is at top: 50%? -


i can see code works align div vertically within parent element:

.element {   position: relative;   top: 50%;   transform: translatey(-50%); } 

the question why? first thought parent element encompassed more viewport. made parent viewport height equal 100vh , width 100%. did not work. still needed translate or negative margin offset. why need negative offset when parent element set margin: 0;? because of computed margin i'm not taking account?

top:0 (default)

by default, element @ top of page, , top of element @ 0:

--------top of page-------- {element}   ------middle of  page------    ------bottom of  page------ 

top:50%

when move down 50% height (50% of entire page), top of element @ 50% mark, meaning element starts @ 50% , not centered.

--------top of page--------    ------middle of  page------ {element}   ------bottom of  page------ 

top:50%; transform:translatey(-50%);

when top of element @ halfway mark, can move element half of own height center whole page. that's transform:translatey(-50%); does:

--------top of page--------    {element}-middle of page---    ------bottom of  page------ 

but why can't top: 25% or that? i've made quick snippet show difference implementation:

body {    margin: 0;  }  .row {    display: flex;    justify-content: space-between;  }  .container {    display: inline-block;    margin: 5px;    width: 200px;    height: 200px;    background: tomato;  }  .inner {    position: relative;    margin: 0 auto;    height: 50%;    width: 50%;    background: #ffc4ba;  }  .inner.small {    width: 25%;    height: 25%;  }  .inner.big {    width: 75%;    height: 75%;  }  .percent {    top: 25%  }  .transform {    top: 50%;    transform: translatey(-50%);  }
<b>first row </b>looks alright, that's because gap works 25%  <div class="row">    <div class="container">      <div class="inner percent"></div>    </div>    <div class="container">      <div class="inner transform"></div>    </div>  </div>  <b>second row </b>made center square bit smaller, , 25% high we'd expect bottom of element reach 75%  <div class="row">    <div class="container">      <div class="small inner percent"></div>    </div>    <div class="container">      <div class="small inner transform"></div>    </div>  </div>  <b>third row </b>now i've made center box big , ends lower 75% making 25% start late  <div class="row">    <div class="container">      <div class="big inner percent"></div>    </div>    <div class="container">      <div class="big inner transform"></div>    </div>  </div>


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -