Relative parent, absolute positioning vertically by percentage?

前提是你 提交于 2019-12-03 01:34:37

The absolutely positioned element is taken out of the natural flow of the document which means your container has zero height and width.

10% and 50% of that zero height and width are, of course, zero.

If you give your container a height and width, your percentage positions will start to work as you want.

Here is a working example.

.container { position: relative; width:500px; height:500px; } 

Welp, my first post in SE. For those of you seeing this in the future, you can actually use viewport height as a measure of percentage.

.container {
    position: relative;
    top: 10vh;  // 10% of height from top of div
}

You will likely need to add height: 100% to your .container div:

.container { height: 100%; position: relative; }

and possibly all the ancestor elements:

html, body { height: 100%; }
David L

@Jaime Dixon's answer was great. Beautiful, two great concepts given there.

  1. The percentage, the relative units are relative TO SOMETHING, you must understand what's the reference container to which those values are calculated.

  2. Even if you have a container, there CAN BE an arbitrary behavior if the container has it's dimensions as "auto". So, to have a predictable behavior, be sure that the container has a dimension better than simply saying "auto". OR, if your container also has 100%, and its parent and so on, make sure you have a css instruction in which you have specified the height of the elements html, body:

example:

html, body {
    height: desired_value;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!