Relative positioning Top with percentage does not work for inline element

In the following case, em will not be changed if I use a percentage for Top. It works great if I use px. Why?

I researched this in w3 and couldn't find any qualifications on using percentages. The positioning context is p - since its relative positioning - which should have the height derived from the lines.

EDIT: To be clear, I understand workarounds, but I am trying to understand the specification. My experience so far is that in general there is some logic, even if it is not immediately obvious. My goal in this question is to figure out what the logic is in reconciling this behavior with the specified behavior in the visual formatting model.

Html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <style>
        body {
            font-size: x-small;
        }
        div{
            outline: 1px solid red;
            background-color: silver;
            overflow: visible;
        }

        #test em {
            position: relative;
            color: red;
            bottom: -10%;
        }
    </style>
</head>
<body>
    <div id="test">
        <p>Lorem ipsum sit amet, <em>duo ut dicant expetenda</em>. Laudem maiestatis eam et. Lucilius patrioque instructior et has. Sea at zril affert, mea accusam nominavi officiis te. Ad nam tota quidam mandamus, pro <em>dolor</em> veri volumus torquatos an.</p>
    </div>
</body>
</html>

      

+3


source to share


1 answer


@Cool Blue,

Your reading of the specification is correct. The offset of a positioned element, as determined top

, is calculated based on the height of that element containing the block (which is generated in this case <p>

). However, the problem you are facing seems like a variation on the well-known problem with how browsers compute a property height

. This problem usually occurs when we are trying to create an element that spans the full height of the viewport .



The problem is that browsers don't bother calculating the height of an element unless you specify absolute height

for the element on the page. Instead, browsers allow content to flow within the width of the viewport until the viewport comes to an end. Thus, if you set top: X%

to <em>

, and the contained elements have height: auto

, the browser does nothing. If you are going to use a percentage for top

(and if you only want to use percentages across the entire tree of elements), you must set height

from each ancestor to a suitable percentage.

HERE is a solution that only uses percentages. Note that the effect is slightly uneven, as resizing the viewport will change the offset <em>

relative to the text inside <p>

. So, while this is an interesting theoretical discussion, it might be better to set top

in pixels from a design perspective.

+1


source







All Articles