问题
i found interesting feature, but cant find why it happens. So: We have fixed position element, which second under body. First element have styles
.firstEl {
width:100%;
height:200px;
background-color:green;
}
Second element have
.fixedEl {
position:fixed;
right:0;
height:100px;
width:50px;
background-color:red;
}
Where do you think will be fixed element positioning by top? It`s intresting behavior when js change height of first element and our fixed container change his position too. https://jsfiddle.net/titusja/ue715fuk/
P.S. If someone can help to find why it happens(i mean documentation of this behavior) i`ll be very greatfull
回答1:
Using fixed position without setting top, left, ..
will have the same behave as absolute position relative to its own initial position.
But setting the top, left, ...
will fix the position relative to the document or the page.
回答2:
The position of an element does not default to 0, 0
. It's position is set by default relative to the containing element, therefore in your example, .fixedEl
has a right: 0
relative to the viewport, and the top is 0px
from the top of .firstEl
.
The default position of this element by default and the viewport not scrolled would be 200px
from the top and the left is obviously dependent on the width of your div. However, if you do not override the top and left, they are already defined by the rendering engine as the top:200px
, left:(width of the viewport - width of .fixedEl)
, the left
property is defined so cause of the right: 0;
Then on window resize, that position is adjusted to reflect the position based on the viewport so as you scroll down the position is changed to keep it fixed.
So, by simply adding "position:fixed;" your properties would (as far as the browser is concerned) be as follows:
position: fixed;
top: 200px; // defined by default during browser rendering in some browsers (based on scroll position on load)
left: (width of the viewport - width of .fixedEl); // defined by default during browser rendering in some browsers (based on scroll position / width of browser at time of load and due to right: 0)
来源:https://stackoverflow.com/questions/42922602/position-fixed-without-top-and-bottom