views:

76

answers:

2

CSS doesn't support arithmetic such as margin-left: -60px + 50% of the width of the parent div. But my desire to do so is overwhelming. Does anyone know a solution using JavaScript or otherwise?

Thanks
Mike

+2  A: 

Try this:

var elem = document.getElementById("foobar"),
    parent = elem.parentNode;
while (parent && parent.nodeName != "DIV") {
    parent = parent.parentNode;
}
if (parent.nodeName == "DIV") {
    elem.style.marginLeft = - 60 + (parent.style.width * 0.5) + "px";
} else {
    elem.style.marginLeft = "-60px";
}
Gumbo
Is there a way to get by Class rather than ID? Thanks again.
Mike
Yes, `getElementById` was just an example. `getElementsByClassName` is implemented in some browser but not in all yet. So you should better use a framework like jQuery. See thedz’s answer.
Gumbo
This internal tool only needs to work in Safari 4. I'm not getting into the while loop. The 'innerBox' class is an absolute div and its parent is the 'container' class relative div. Here's the code I modified (sorry I don't see how to make it appear as code in comments): var elem = document.getElementsByClassName("innerBox"), parent = elem.parentNode; while (parent } if (parent.nodeName == "DIV") { elem.style.marginLeft = - 60 + (parent.style.width * 0.5) + "px"; } else { elem.style.marginLeft = "-60px"; }
Mike
`getElementsByClassName` returns a list of elements with that class. So you have to iterate over that list (simple `for` loop) and put everything into that loop. So: `var elems = document.getElementsByClassName("innerBox"); for (var i=0; i<elems.length; i++) { var elem = elems[i], parent = elem.parentNode; … }`.
Gumbo
A: 

It's certainly possible with JS, but the specific code will differ depending on what you use (vanilla, frameworks, etc.). Here's a jQuery example:

 $('#div').css('width', (-60+($('#div').parent().width()*.5))+'px');
thedz