Madhavan Kumar Madhavan Kumar - 3 months ago 11
CSS Question

Jquery UI position plugin is not working with margin property

I am trying to position a box on the top right screen of my browser using the jquery ui position plugin as,

$('.container').position({
my : 'right top',
at : 'right top',
of : 'body'
});


This works properly and is getting displayed on the top right. But i like to give some space between the box and the right side screen edge. So, i added
margin-right
position to the container. Immediately, the box moved from the top right corner to left corner.

Plunker code is here.

Why does margin property affect the container's absolute coordinates?

Answer

Setting the margin to the container will cause jquery-ui to wrongly calculate the position of the element, however when you have the ability to do so using the position function itself:

at : 'right-10px top'

Besides that, in order to make sure jquery will position the element in the right place, the content should be inside the element before positioning.

In this example you have 2 buttons. The first button will position a box in the right corner, while the second button will position a box in the right corner-10px.

$('.myButton1').click(function(){
	console.log('adding new element into the div container')
	$('.container1').append('<div class="noti-msg">this is a long small notification message... this width will fall down to the next level</div>');
  $('.container1').position({
	my : 'right top',
	at : 'right top',
	of : 'body'
}); 
});
$('.myButton2').click(function(){
	console.log('adding new element into the div container')
	$('.container2').append('<div class="noti-msg">this is a long small notification message... this width will fall down to the next level</div>');
  $('.container2').position({
	my : 'right top',
	at : 'right-10px top',
	of : 'body'
}); 
});
.container1, .container2 {
  width: 300px;
  background-color: #c3c3c3;
  justify-content: center;
  text-align: center;
  opacity: 0.9;
}
.container2 {
  background: red;
}
.noti-msg{
  padding: 5px;
  box-sizing: border-box;
  width: 250px;
}
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.css' />
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.2.0" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/external/jquery/jquery.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.js'></script>
<button class="myButton1">my button 1...</button>
<button class="myButton2">my button 2...</button>
<br/>
<div class="container1">
</div>
<div class="container2">
</div>