Skip to content Skip to sidebar Skip to footer

Relative Positioning Top With Percentage Doesn't Work For In-line Element

In the following, the em is not repositioned if I use a percentage value for Top. It works fine if I use px. Why? I researched this in w3 and could not find any qualification on u

Solution 1:

@Cool Blue,

Your reading of the specification is correct. A positioned element's offset as defined by top is calculated based on the height of that element's containing block (which in this case is generated by <p>). However, the problem you are encountering seems like a variation on a well known issue with the way browsers calculate the height property. This problem typically occurs when we are trying to create an element that takes up the full-height of the viewport.

The issue is that browsers don't bother to calculate the height of an element unless you specify an absolute height for an element on the page. Instead, browsers let the content flow within the width of the viewport until the viewport comes to an end. Thus, if you set top: X% on <em>, and the containing elements have height: auto, the browser does nothing. If you are going to use a percentage value for top (and if you only want to use percentages throughout the entire element tree) you must set the height of every ancestor to a suitable percentage.

HERE is a solution that uses only percentages. Note that the effect is a bit uneven since changing the viewport size will change the offset of <em> relative to the text within <p>. So, while this is an interesting theoretical discussion, it may be better to set top in pixels from a design perspective.

Post a Comment for "Relative Positioning Top With Percentage Doesn't Work For In-line Element"