Good time! There is a fixed position of the element:
element{ position: fixed; top: 0; left: 0; width: 100%; height: 100%; } It is not initially present on the page, but is dynamically loaded (by click) and placed inside the "parent" block. Among his parents there is one with relative positioning:
<body> <div class="wrapper" style="position:relative"> <div id="parent"></div> </div> </body> The hidden class is initially attached to the element (it already comes in this form).
.hidden { display: none; } After loading the element should be displayed on the page, occupying, respectively, the entire area of the browser. It is processed by the following script:
var w = $(element).innerWidth(); var h = $(element).height(); $(element).css({ 'top' : '50%', 'left' : '50%', 'margin-top' : -(h/2), 'margin-left': -(w/2) }); $(element).removeClass('hidden').addClass('shown'); The class shown only sets display: block .
The problem is that, for some reason, the width and height of an element are counted not from the browser window area (which I, frankly, expected with fixed positioning, but from the same wrapper element, which has relative positioning. Because of this, at the time of calculation the element is equal to the height of the entire document and, accordingly, the margins are calculated incorrectly, the element is too high. After the hidden class is removed, the height becomes equal to the height of the browser window, as it should be. The element disappears beyond the upper limit screen.
Why does a fixedly positioned element (even invisible, even not loaded) calculate its dimensions relative to another element, and not relative to the screen? Or is this normal behavior and I need to change the entire layout?
A temporary crutch that allows you to properly display an element:
$('.wrapper').css('position','static'); var w = $(element).innerWidth(); var h = $(element).height(); $('.wrapper').css('position','relative'); $(element).css({ 'top' : '50%', 'left' : '50%', 'margin-top' : -(h/2), 'margin-left': -(w/2) }); $(element).removeClass('hidden').addClass('shown'); ADF: Added display: block element, nothing changes. At body and html height is indicated : 100% .
ADF: Apparently, the problem is not in the most relatively positioned element, but in the fact that if a fixed block has display: none, the script returns not its real height, but the height of the nearest positioned element. Is it possible to somehow get the real height of a hidden fixed block?