user3241507
user3241507

Reputation: 363

Center div vertically and horizontally center even when page scrolled down

I am trying to display a div vertically and horizontally center, and this works fine, but when I scroll down the page and try the link at the bottom (it is a comment box) then it displays at the top of the page, not in the screen, and you need to scroll up to use it. How can I get it centered even if the user has scrolled down?

Here is my code so far (from the research I have done):

$("#comment").css('top', ((screen.height / 2) - ($('#comment').height()/2))+'px');
$("#comment").css('left', (screen.width / 2) - ($('#comment').width()/2)+'px');

Thanks in advance!

Upvotes: 1

Views: 606

Answers (2)

Olavxxx
Olavxxx

Reputation: 196

Do you need to do this via JQuery? Maybe you can just CSS style it?

CSS

#commentBox {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
    height:240px;
    width:70%;
    padding:15px;
    border:1px dashed #333;
    background-color:#eee;
}

Look at my example: FIDDLE

Upvotes: 3

.scroll()

var comment = $("#comment"),
    com = $('#com');
$(window).scroll(function () {
    comment.css('top', ((screen.height / 2) - (com.height() / 2)) + 'px');
    comment.css('left', (screen.width / 2) - (com.width() / 2) + 'px');
});

Upvotes: 0

Related Questions