and with Pure CSS?-CSS Tutorial-php.cn">

Home  >  Article  >  Web Front-end  >  How to Achieve a Consistent \"Background-Size: Cover\" Effect for

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

Susan Sarandon
Susan SarandonOriginal
2024-10-30 16:02:03630browse

How to Achieve a Consistent and How to Achieve a Consistent \ and with Pure CSS?" > with Pure CSS? " /> and How to Achieve a Consistent \ and 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>

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>

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

Statement:
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