Don P
Don P

Reputation: 63547

Set margin-top to a % of the parent element's height

I want an element's margin-top to be a % of the parent elements height.

For example if I have div that has height 100px, I want to create a p element inside of it that has margin-top: 25px, except by setting the p element's margin with % so it can handle its parent changing height.

Edit: For those that think this is obvious - you can't use margin-top: 25%. %'s for the box model except height use the parent element's width. So you are setting it to 25% of the parent div's width if you use margin-top: 25%.

Upvotes: 7

Views: 3103

Answers (3)

Nillervision
Nillervision

Reputation: 441

You can use JS to measure the parent element's height after it has been rendered (offsetHeight) and then divide it by 4 and assign the result to the childs top or marginTop property.

var parent = document.getElementById("parent");
var child = document.getElementById("child");
var marginVal = (parent.offsetHeight)/4;
child.style.top = marginVal+"px";

Fiddle: http://jsfiddle.net/Nillervision/AwqJK/

If you wrap the js in a function you can call it when the page is loaded (window.onload) and when the browser get resized if that changes the parent elements size (window.onresize)

Upvotes: 0

JoeJ
JoeJ

Reputation: 940

Try positioning the element instead of giving it a margin, like so:

p {
  position: relative;
  top: 50%;
}

Demo for reference

Upvotes: 0

Ravi Hamsa
Ravi Hamsa

Reputation: 4721

This is what I see as one of the solution:

 <div style="height:100px; background-color:red; color:white; position:relative;">
     <div style="top: 25%;position: absolute;">
         <p> I want an elements margin-top to be a % of t</p>
     </div>
 </div>

Upvotes: 4

Related Questions