jQuery Style How to - Set margin top








Question

We would like to know how to set margin top.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery.js'></script>
<style type='text/css'>
#block {<!--  w  w w.  j  a v  a2s .c  o  m-->
  height: 50px;
  width: 50px;
  background-color: red;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    var blockheight = $("#block").height();
    var margintop = (blockheight / -2);
    console.log(margintop);
    $('#block').css("margin-top", margintop);
});
</script>
</head>
<body>
  <div id="block"></div>
</body>
</html>

The code above is rendered as follows: