简体   繁体   中英

Position absolute top property based on the parent width

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

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.

尝试为父元素添加position: relative

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM