CSS Background-Size: Cover Background-Attachment: Fixed Clipping Background Images
Can you encounter a situation where background images with background-size: cover and background-attachment: fixed get clipped?
The Issue:
As the question suggests, in a scenario with figures using background images, the combination of background-size: cover and background-attachment: fixed leads to clipping of the background images when there's an offset. This is an inherent behavior of CSS, as documented by Mozilla.
The Goal:
The desired outcome is for images to clip either vertically or horizontally, but not both, while maintaining centered alignment within the figure itself.
The Solution:
Unfortunately, achieving this result solely with CSS is not possible. As detailed in the answer, fixed positioning in CSS creates a disconnect between the background image and the container element. Therefore, even with the cover value, the image size is determined relative to the viewport rather than the figure's dimensions.
JavaScript Alternative:
The recommended solution is to use JavaScript to simulate the fixed positioning effect while calculating background-size: cover relative to the figure element. This involves listening for scroll events and manually adjusting the background position to match the viewport scroll.
The above is the detailed content of Does `background-size: cover` and `background-attachment: fixed` cause background image clipping, and how can it be solved?. For more information, please follow other related articles on the PHP Chinese website!