Home  >  Article  >  Web Front-end  >  How to Achieve the `background-size: cover` Effect with `` and `` Elements Using CSS?

How to Achieve the `background-size: cover` Effect with `` and `` Elements Using CSS?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 20:10:31419browse

How to Achieve the `background-size: cover` Effect with `` and `` Elements Using CSS?

How to Replicate background-size:cover on

When working with HTML elements like

CSS Approach

Using CSS alone, you can create a perfect cover simulation for videos without relying on scripts. The trick lies in precisely calculating the width and height of the video relative to the aspect ratio of the parent element. For instance, if your video has a 16:9 aspect ratio:

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

Centering the Video

If you also need to center the video, the following CSS will provide a reliable approach:

<code class="css">/* merge with above CSS */
.parent-element-to-video {
  position: relative; /* or absolute or fixed */
}
video {
  position: absolute;
  left: 50%; /* % of surrounding element */
  top: 50%;
  transform: translate(-50%, -50%); /* % of current element */
}</code>

Compatibility Considerations

While this solution works flawlessly in CSS3 compliant browsers, older browsers may require a script-based approach to achieve the desired result.

The above is the detailed content of How to Achieve the `background-size: cover` Effect with `` and `` Elements Using CSS?. For more information, please follow other related articles on the PHP Chinese website!

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