Results 1 to 3 of 3

Thread: Centering a DIV with JS/jQuery

  1. #1
    Join Date
    Mar 2008
    SoCal in an RV

    Centering a DIV with JS/jQuery

    I'm trying to write a function to center a div within a parent div, and I'm having a little trouble. Horizontally, it works fine. Vertically, not so much. This is my function:

    function centerObject(idName, idParent) {
    var parentLeft = $(idParent).position().left;
    var parentWidth = $(idParent).width();
    var parentWCenter = parentWidth / 2;

    var parentTop = $(idParent).position().top;
    var parentHeight = $(idParent).height();
    var parentHCenter = parentHeight / 2;

    var objWidth = $(idName).width();
    var objWCenter = parentLeft + parentWCenter - (objWidth / 2);

    var objHeight = $(idName).height();
    var objHCenter = Math.abs(parentTop + parentHCenter - (objHeight / 2) - 20);



    The line with the Math.abs call is necessary because without it, the given div ends up halfway off the page up at the top. At least this way it appears somewhere within the browser.

    The divs in question are all set to position: absolute, but I've tried setting them to all the other possibilities without luck. Or maybe I missed something. This happens in any browser... IE, FF, Chrome, Safari, etc.

    In any case, anybody have any ideas on where I went wrong?


    Last edited by snarfblat; 04-15-2010 at 11:01 AM.

  2. #2
    Join Date
    Mar 2007
    Can you post the html?
    "Hippies.They're everywhere. They wanna save the earth, but all they do is smoke pot and smell bad."-Cartman

  3. #3
    Join Date
    Mar 2008
    SoCal in an RV
    The HTML is simple...

    <div id="whatever"></div>

    At the moment the only thing living inside the div is a span and a heading, e.g. "About Us".

    Now, the css for it:

    #about {
    display: none;
    position: absolute;
    padding: 10px;
    border: 2px solid black;
    color: black;
    background-color: white;
    width: 600px;
    height: 350px;

    Does that help?



Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center