Seepage Ratio Element - Vertical Centering

I am trying to vertically center an element that uses padding-bottom to create the desired aspect ratio (for video). I want to have top and bottom black borders, for example when a movie is displayed in a higher aspect ratio than it was filmed:

body{
    padding:0;
    margin:0;
    position:relative;
    display:block;
}
main{
    background: url(http://placekitten.com/1280) no-repeat center center;
    background-size: cover;
    width:100%;
    padding-top:56.25%;
    width:100%;
}

      

http://jsfiddle.net/y4tcufo5/ - test case

I've tried top: 50%; transform: translateY (-50%); tricks on the element but nothing works! I know this should be done using padding instead of width and height, but I can't seem to bind the element to the design in any other way.

Is it possible to solve this problem either with:

  • Using the fill trick and another way to vertically center an element
  • Discarding the spacer and achieving the aspect ratio by other means
  • Use a flash box or something like that

Any help is greatly appreciated!

+3


source to share


1 answer


Vertically center something with these 4 lines of code

position: relative;
top: 50%;
transform: translateY(-50%);
max-height: 100%;

      

Apply this to the wrapper of the element you want to vertically center

( Demo )



Html

<div class="wrap">
    <main></main>
</div>

      

CSS

html, body {
    padding:0;
    margin:0;
    height: 100%;
}
main{
    background: url(http://placekitten.com/1280) no-repeat center center;
    background-size: cover;
    width:100%;
    padding-top:56.25%;
}
.wrap {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    max-height: 100%;
}

      

+2


source







All Articles