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 using percentage values. The positioning context is the p - since its relative positioning - which should have Height derived from the line boxes.
EDIT: Just to be clear, I realise the work-arounds, but I am trying to understand the specification. My experience so far is that there is generally some logic there even if its not immediately obvious. My aim with this question is to find out what is the logic in reconciling this behaviour with the specified behaviour 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>
@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.
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