"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2025-01-09
Browse:358

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:

.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 */
}

Centering the Video

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

/* 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 */
}

Compatibility Considerations

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

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3