I'm trying to create a vertically positioned DIV by percentage. I have the parent container to set to relative and the content div set to absolute. This works fine when I position the content div with pixels, but when I try percentages the percentages are disregarded:
.container { position: relative; } .content { position: absolute; left: 10%; top: 50%; } <div class="container"><div class="content"> This is the content div. It should be 10% from the left of the container div. </div></div>
The content div appears at the top of the page, disregarding the 50% vertical placement. What am I missing? Thanks in advance!
Absolute In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow.
position: relative places an element relative to its current position without changing the layout around it, whereas position: absolute places an element relative to its parent's position and changing the layout around it.
As a special, use “relative” positioning with no displacement (just setting position: relative ) to make an element a frame of reference, so that you can use “absolute” positioning for elements that are inside it (in markup).
Static - this is the default value, all elements are in order as they appear in the document. Relative - the element is positioned relative to its normal position. Absolute - the element is positioned absolutely to its first positioned parent.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With