Home > Web Front-end > CSS Tutorial > How to Achieve a Consistent \'Background-Size: Cover\' Effect for

How to Achieve a Consistent \'Background-Size: Cover\' Effect for

Susan Sarandon
Release: 2024-10-30 16:02:03
Original
719 people have browsed it

How to Achieve a Consistent and How to Achieve a Consistent \'Background-Size: Cover\' Effect for <video> and <img> with Pure CSS? with Pure CSS? " /> and How to Achieve a Consistent \'Background-Size: Cover\' Effect for <video> and <img> with Pure CSS? with Pure CSS? " />

Cover Background Simulation for

Achieving a consistent "background-size: cover" effect for elements like

CSS Solution without Edge Cases:

Instead of relying on scripts, a CSS solution with no edge cases can be implemented using the following steps:

  1. Set the parent element to have overflow: hidden.
  2. Set the video or image element to height: 100%;.
  3. Calculate the width based on the aspect ratio (e.g., 100 * 16 / 9 for 16:9 videos).
  4. Set min-width: 100%; to prevent resizing smaller than the parent.
  5. Set min-height to ensure the height scales down proportionally.

Example:

<code class="css">.parent-element-to-video {
    overflow: hidden;
}

video {
    height: 100%;
    width: 177.77777778vh; /* 100 * 16 / 9 */
    min-width: 100%;
    min-height: 56.25vw; /* 100 * 9 / 16 */
}</code>
Copy after login

Centered Video:

To center the video, use the following CSS:

<code class="css">.parent-element-to-video {
    position: relative;
}

video {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}</code>
Copy after login

The above is the detailed content of How to Achieve a Consistent \'Background-Size: Cover\' Effect for

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