Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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%.

like image 552
Don P Avatar asked Jul 19 '14 21:07

Don P


People also ask

Which property is used to set top margin of your element?

The margin-top property sets the top margin of an element.

How can we set the margin of an element?

Adjusting the Margin Size of an HTML Element With CSS You can remove this margin by setting the top and left margin to zero. Like the padding and border, the sizes of specific sides of the margin can be set using margin-left , margin-right , margin-top , and margin-bottom .

How do you set the margin-top and margin-bottom values of a purely inline element?

Q: How do you set the margin-top and margin-bottom values of a purely inline element? A: You can't. Inline elements can only have left and right margins.

What is margin-top in HTML?

The margin-top CSS property sets the margin area on the top of an element. A positive value places it farther from its neighbors, while a negative value places it closer.


1 Answers

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>
like image 135
Ravi Hamsa Avatar answered Oct 17 '22 17:10

Ravi Hamsa