MarksCode MarksCode - 6 months ago 17
CSS Question

Make div stay contained within its parent mouse move

I have a div within another div and when the user hovers over the parent the inner div follows the mouse position. However, when the mouse is on the edge of the parent the child's border goes beyond the parents. I want to make it so the child div's border always stays contained within its parents.

I made a fiddle of what I've made so far:

A solution I'm thinking about is checking if the inner div's

attribute is a certain length from the outer's
, and if it is then stop the mouse position tracking, same goes for left, right, and bottom.

Can anyone tell me if there's a good way to keep the child's borders contained within its parents?


var innerDiv = $('#inner');
var outerDiv = $('#outer');
var outDim = outerDiv.offset();
outDim.right = (outDim.left + outerDiv.width());
outDim.bottom = ( + outerDiv.height());
$(document).on('mousemove', function(e) {
  var x = (e.clientX) - 15;
  var y = (e.clientY) - 15;
  var x_allowed = x >= outDim.left && x <= (outDim.right - innerDiv.width());
  var y_allowed = y >= && y <= (outDim.bottom - innerDiv.height());
  if (y_allowed) {
      top: y + 'px',
  if (x_allowed) {
      left: x + 'px'

#wrap {
  height: 200px;
  width: 200px;
  border: 2px solid black;
#outer {
  height: 100px;
  width: 100px;
  border: 2px solid blue;
  margin: 0 auto;
#inner {
  height: 40px;
  width: 40px;
  border: 2px solid red;
  position: absolute;
<script src=""></script>
<div id="wrap">
  <div id="outer">
    <div id="inner">