简体   繁体   中英

Align content vertically JavaScript

Hy,

Basically what I want to achieve is to align some content vertically, in my case name & job.

The issue here is, when resizing the window, I want the content to stay in the middle. I found a small script but I cannot get it to work, still learning the basics of JS.

My markup is the following:

  1. Navigation
  2. Vertically content
  3. Footer (position: absolute; bottom: 0;) // is aligned to bottom.

I created a JSFiddle ( http://jsfiddle.net/marianstroiu/khm52p0a/1/ ), so can you see what I'm talking about.

function getWindowHeight() {
            var windowHeight = 0;
            if (typeof(window.innerHeight) == 'number') {
                windowHeight = window.innerHeight;
            }
            else {
                if (document.documentElement && document.documentElement.clientHeight) {
                    windowHeight = document.documentElement.clientHeight;
                }
                else {
                    if (document.body && document.body.clientHeight) {
                        windowHeight = document.body.clientHeight;
                    }
                }
            }
            return windowHeight;
        }
        function setContent() {
            if (document.getElementById) {
                var windowHeight = getWindowHeight();
                if (windowHeight > 0) {
                    var contentElement = document.getElementById('v-content');
                    var contentHeight = contentElement.offsetHeight;
                    if (windowHeight - contentHeight > 0) {
                        contentElement.style.position = 'relative';
                        contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
                    }
                    else {
                        contentElement.style.position = 'static';
                    }
                }
            }
        }
        window.onload = function() {
            setContent();
        }
        window.onresize = function() {
            setContent();
        }

Thank you!

You are using bootstrap sticky-footer template that add bottom margin and footer to the body element so you should substract 2 * 60 pixel from window height. Here is modified jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM