3

Having the following HTML

<div class="child-of-body">
    This is a text
</div>

and the following CSS

.child-of-body {
    position: absolute;
    top: 10%;
}

I can set the top value of the selected elements. I see that 10% is computed based on the parent height.

How can I set the top property in percent values based on the parent width?

I know that is possible via JavaScript, but would it be possible with CSS only?

JSFIDDLE

GhitaB
  • 3,275
  • 3
  • 33
  • 62

2 Answers2

7

I think you're looking for margin-top property.

A percentage value on top/bottom padding or margins is relative to the width of the containing block.

.child-of-body {
    position: absolute;
    margin-top: 10%;
}

JSFiddle Demo.

Also, it's worth to take a look at Louis Lazaris' Vertical Percentages in CSS article.

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
1

try to add position: relative for the parent element.

Cristina Cristea
  • 566
  • 1
  • 3
  • 11