Set the minimum vertex to a vertically centered div

I have <div>vertically centered with the following CSS:

.v-centered {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

This is wonderful until its height, which was not known in advance, does not lead to the fact that its translation pushes it away from the top of the screen if the screen is too small.

I have javascript (with jQuery) to reduce this:

var $myDiv = $('#myDiv'),
    paddingTop = parseInt($('html').css('padding-top'));

window.onresize = () => {
    if ($myDiv.is('.v-centered')) {
        if ($myDiv.position().top < paddingTop) {
            $myDiv.removeClass('v-centered');
        }
    } else {
        if ($myDiv.height() < document.body.offsetHeight) {
            $myDiv.addClass('v-centered');
        }
    }
}

However, this is a bit ugly and, on a scale of window resizing, it updates rather slowly. I would like a pure CSS / HTML approach or, if it is not, a function window.onresizethat does not do so many calculations.

jsFiddle

+4
source share
1 answer

CSS , flexbox, , undefined ? Flexbox - CSS, JS.

Flexbox, :

.parent {
    display: flex;
    align-items: center;
}

, , .

.child {
    margin: auto;       /* for full vertical and horizontal centering */
 /* margin: auto 0; */  /* for vertical centering only */
 /* margin: 0 auto; */  /* for horizontal centering only */
}

DEMO

( ) Flexbox :


, Flexbox , IE 8 9. , Safari 8 IE10, . , , CSS : Autoprefixer.

+1

Source: https://habr.com/ru/post/1624829/


All Articles