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

4
  • Maybe using something like SCSS might work?
    – qwertynl
    Jan 29, 2014 at 14:32
  • Could you be more elaborative because why generally you worry about top and width. Jan 29, 2014 at 14:39
  • Is the divs width dynamic or a set size? Jan 29, 2014 at 14:40
  • @ArunKumar I am just curious. :)
    – GhitaB
    Jan 29, 2014 at 14:44

2 Answers 2

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.

0
1

try to add position: relative for the parent element.

2
  • When I resize the browser window width I want to see the text moving vertically and to have the same aspect ratio.
    – GhitaB
    Jan 29, 2014 at 14:49
  • I don't think this will work if this is what you need. Jan 29, 2014 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.