Does `background-size: cover` and `background-attachment: fixed` cause background image clipping, and how can it be solved?

Mary-Kate Olsen
Release: 2024-11-27 05:41:09
Original
650 people have browsed it

Does `background-size: cover` and `background-attachment: fixed` cause background image clipping, and how can it be solved?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template