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

Mary-Kate Olsen
Release: 2024-10-30 20:10:31
Original
436 people have browsed it

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>
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!