Rotating video in CSS instead of re-encoding
cssvideocontainer-queriestransform
When a video was recorded sideways, the honest fix is a re-encode, which is slow and lossy and impossible on a 1 GB server for a 200 MB file. The alternative used on videos.jhampton.io: store a rotate field (0/90/180/270) on the record and apply it in CSS everywhere the video appears (card, blur placeholder, poster, admin row, editor preview, watch page, overlay, fullscreen). The file is never rewritten.
The technique
A quarter turn of a 16:9 box leaves a 9:16 picture with empty corners. So first give the picture the container's dimensions swapped, then rotate, and it lands back over the box exactly.
- The frame gets container-type: size so the child can use container-query units (100cqh wide, 100cqw tall) for the swapped size.
- Scope every rule to [data-rot] so upright videos keep the simpler layout.
- A rotated video needs a frame with a definite size. On a page layout, set a CSS variable (--vp-ar) from videoWidth/videoHeight (already swapped) at loadedmetadata. In an overlay or fullscreen, give the frame its size directly and do not also set an aspect ratio.
- Put these rules last in the stylesheet: earlier rules such as .vp:fullscreen video set width/height at the same specificity and must lose.
Consequences to state, not "fix"
- A download comes out as it went in (sideways).
- A no-JS watch page shows the original orientation.
- iOS native fullscreen (
webkitEnterFullscreen) ignores your CSS, so skip it for rotated videos. - Bulk rotate should accumulate (four presses return to upright); absolute values go through an editor.
Related: rotation metadata in source files
Phone camera files often carry a display matrix (e.g. -90 degrees) rather than rotated pixels. A standard H.264 encode with ffmpeg bakes that rotation into the pixels, so such a record needs no rotate field. Snapchat exports can do the opposite: landscape footage at portrait dimensions with no matrix at all. See Encoding phone clips for the web (HEVC remux, H.264 fallback).
See also
- Web video players: sound, mute, fullscreen and autoplay-next
- A JSON file as the database (flat-file catalogs)