Home >Web Front-end >CSS Tutorial >Why is 'position: sticky' not working when I define a 'height'?
'position: sticky' not working when 'height' is defined
Many web developers often face a problem when trying to make an element sticky using CSS. In this case, the issue arises when setting a fixed height for the element. This problem can be encountered in instances like implementing a persistent footer on a landing page or a column on a sidebar.
The solution lies in understanding how the 'position: sticky' property works. According to the CSS specifications, an element with this property is positioned relatively until it reaches a specified threshold, at which point it becomes "stuck" until it reaches the opposite edge of the containing block.
The containing block is essentially the parent element of the sticky object. In web designs, the 'body' tag often becomes this containing block due to its inherent flexible height. However, when a specific height is applied to the body or any intermediate container, it creates an overflow situation for the web page content.
In the example provided, the body was set to 100% height, and both the main content and footer were given fixed heights of 92% and 8%, respectively. This layout made it so that the footer was already at the opposite edge of its containing block, preventing the sticky positioning from taking effect.
To resolve this issue, avoid setting fixed heights for the body or parent containers and instead use flexible values such as percentages or viewport units. This allows the browser to determine the actual height based on the content and window size, ensuring that the sticky element can function correctly.
The above is the detailed content of Why is 'position: sticky' not working when I define a 'height'?. For more information, please follow other related articles on the PHP Chinese website!