badbye badbye - 3 months ago 9
CSS Question

Javascript: show the element in the middle of screen doesn't work with fixed postion

I need the element vertically on the middle of the screen when the button is clicked, and no matter how browser's height is adjust, it will always in the middle.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button id="button">click me</button>
<div id="element">balah</div>
</html>


<style>
#element{
position: fixed;
color: red;
}
</style>


I tried:

<script>
$("#button").click(function(){
$('#element').css('margin-top',$(window).innerHeight()/2);

})
</script>

Answer

No need to use JS, this can be done with pure CSS;

.fixed {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
Comments