P
P
Polina Emelyanova2017-10-11 07:09:08
css
Polina Emelyanova, 2017-10-11 07:09:08

How to "fix" the width of a block when assigning position: fixed; and control his behavior?

Hello colleagues.
Please help me understand the position: fixed; Speck is so wise that I'm at a loss.
SUBZH: There is a block located, let's say, in the sidebar, the second in a row. Here it is necessary to "nail" it when scrolling.
No problem, tiddly script - done! BUT!!!! When scrolling, it changes dramatically:
a. Position (which, in principle, is natural, since the report is from the screen, and this can be fought.)
b. Dimensions (But this is a misunderstanding!).
Working sample:
https://codepen.io/emelyanova/pen/NayOQY
QUESTION:
1. How to control the size of the sticky block? Especially if you need adaptive.
2. How to control the behavior and make the block "slide" smoothly without jumping at the start?
CONDITIONS: no libraries needed . I want to figure it out myself. Tell me what I missed in the spec Thank you in
advance!!!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alvvi, 2017-10-11
@alvvi

In general, the behavior is completely logical. You write yourself
the relative size (like yours) will also be calculated from the screen.
As far as I understand, position: sticky is supposed to solve this problem, (correct if not), but it still doesn’t work everywhere.
1. In any solution without JS, some fixed value will be needed, one of the options is to add a fixed max-width to the container, and to the block

width: inherit;
max-width: inherit;

Thus, the block will inherit the max-width of the container and will not go beyond it.
The "jump" in your case is moving 12px from the edge of the screen because you are adding a class with
position: fixed 
top: 12px
only when scrollTop becomes equal to offsetTop and after that it naturally jumps down by 12px. To avoid this, you need to add the class when the scrollTop is equal to (offsetTop - 12px), because in this case the block will already be in the "right" place when added.
https://codepen.io/Alvvi/pen/MEXeaV

A
Abdula Magomedov, 2017-10-11
@Avarskiy

.fixed {
  position: relative;
  //width: 100%;
  margin: 0 auto;
  border: 1px solid #0C0;
  background: #EAFFEA;
}

because here position: relative; and the size it takes relative to the parent. and when you make a block fixed, the size is relative to the window.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question