Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align middle a div in another div (glitch)

Tags:

html

jquery

css

enter image description here

You can find jsFiddle demo here

As you probably see on the picture I trying to align middle a circle (div, green) into another circle (div, grey). I calculated the center of both div and made them equal, but the little green circle is still not in the middle.

Where is the mistake? I just can't find it.

The jquery I use to align circle (where o is the green circle, and $(this) is the grey one:

$.fn.center = function(o) {
  var _X = parseInt(o.css('left')) + parseInt(o.width())/2 - parseInt($(this).width())/2;
  var _Y = parseInt(o.css('top')) + parseInt(o.height())/2 - parseInt($(this).height())/2;
  $(this).offset({ top: _Y, left: _X });
};

Thank you in advance for any help!

like image 644
Pho3nixHun Avatar asked May 20 '13 19:05

Pho3nixHun


2 Answers

Use jQuery UI's position method. It allows you to position any element relative to any other element and abstracts all of the complications. (Courtesy of ogc-nick).

$.fn.center = function(o) {
    $(this).position({
      my: "center middle",
      at: "center middle",
      of: o
    });
};
like image 88
2 revs Avatar answered Sep 27 '22 18:09

2 revs


This might work better for you: HTML:

   <div id="range_sword"> 
    <div class="jk"></div>
   </div>

CSS:

.range_sword, body, div{
    padding:0px;
    margin:0px;
}

.jk{
    display: block;
    min-width: 20px;
    min-height: 20px;
    border-radius: 10px;
    background-color: green;
}

#range_sword{
    background-color: transparent;
    border-radius: 100px;
    position: absolute;
    border-style: dashed;
    border-color: transparent;
    border-width:2px;
    padding:15px;
}
#range_sword:hover{
    background-color:#cdcdcd;
    border-color: #adadad;
}

JS:

$("#range_sword").draggable();

jsfiddle: http://jsfiddle.net/H8Tsc/2/

like image 42
Robert McKee Avatar answered Sep 27 '22 18:09

Robert McKee