
Question:
I want to set the margin-left
of an element to negative half the width of itself. This gets the document's width instead:
$("#services .backPanel > div").css({
'margin-top': -($(this).height()/2),
'margin-left': -($(this).width()/2)
});
What am I doing wrong?
<h2>css</h2>#services{
margin: 127px 0 0 0;
width: 100%;
height: 100%;
position: relative;
}
#services .services{
position: relative;
margin: 40px 9% 0 9%;
}
#services .backPanel{
float: none;
position: absolute;
top: 0;
left: 0;
padding: 30px 50px;
z-index: 80;
width: 100%;
height: 100%;
background: #f9f8f8;
}
#services .backPanel div{
width: 100%;
position: absolute;
top: 50%;
left: 50%;
}
<h2>html</h2>
<div id="services">
<div class="services">
Services
<div class="row-fluid">
<div class="span4">
<div class="frontPanel design">
<h3>Design and development</h3>
</div>
<div class="backPanel">
<div>
<h3>Design and development</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eget viverra massa.
</div>
</div>
</div>
</div>
</div>
</div>
SOLVED ITTurns out that I hadn't taken into account the css transition
property that was set to the parent .backPanel
, which caused the function to read the element's width and height at it was being loaded. With the transition
set for all properties, the inner div
was still growing from 0 towards its final width and height.
<em>Note for future reference</em>: Always take into account the transition for the animations of objects when reading their dimensions.
Answer1:If I'm not mistaking $(this)
is pointing to window
in your case. Try:
$("#services .backPanel > div").each(function() {
var element = $(this);
element.css({
'margin-top': -(element.height()/2),
'margin-left': -(element.width()/2)
});
});
<a href="http://jsfiddle.net/peQ2R/" rel="nofollow">http://jsfiddle.net/peQ2R/</a>
Answer2:Turns out that I hadn't taken into account the css transition
property that was set to the parent .backPanel
, which caused the function to read the element's width and height at it was being loaded. With the transition set for all properties, the inner div was still growing from 0 towards its final width and height.
<em><strong>Note for future reference</strong></em>: Always take into account the transition for the animations of objects when reading their dimensions.