yella-dom
yella-dom

Reputation: 91

Javascript - Center div horizontal and vertical with pure javascript

I'm trying to center a div horizontally and verticlaly without knowing the height/width. I've achieved it within jquery but am struggling to convert it to pure js as I don't want dependancy.. any ideas?

<script>
    $(document).ready(mt);
    $(window).resize(mt);
    function mt(){
    var contentLocked = $('.lockerPopup').outerHeight(); 
        marginTop = ( $(document).height() - contentLocked ) / 2;
        $('.lockerPopup').css({'top': marginTop});}
</script>

Upvotes: 0

Views: 580

Answers (3)

Leo Javier
Leo Javier

Reputation: 1403

You don't need javascript for that, you can do it only using CSS: http://jsfiddle.net/leojavier/gjah19y7/

<div class="container">
    <div class="element"><p>test</p></div>
</div>

CSS

html,body{
    height:100%;
    width:100%;
}
.container {
    display:table;
    height:100%;
    width:100%;
    background:#CCC;
}

.element {
    display:table-cell;
    vertical-align:middle;
    text-align:center;
    width:100px;
    height:100px;
    color:#222;
}

Upvotes: 0

bransonl
bransonl

Reputation: 566

Use .offsetWidth and .offsetHeight to get the dimensions of your element and window.innerWidth and window.innerHeight for the dimensions of the window. The rest of the logic is pretty straight forward to center it using .style.top and .style.left.

See http://codepen.io/anon/pen/JYjqWZ

Alternatively, if you want to center multiple things or you don't need it to be positioned absolutely, I would suggest looking into flexbox or use

top: 50%;
left: 50%;
transform: translate(-50%, -50%);

in your CSS to stay away from JS entirely.

Upvotes: 1

Huan Zhang
Huan Zhang

Reputation: 1085

you can center by using left 50%; top 50% and -webkit-transform: translate(-50%,50%); (obviously add all of the other versions of webkit transform for cross-browser compatibility.

This will always center the div no matter what its width/height and parent container size.

Upvotes: 0

Related Questions