Set Video height in HTML5

31,104

Solution 1

You can't change aspect ratio in <video> tag.

However you can read your video content and write it to <canvas> element.

For example:

<canvas id="canvas" height="768" width="1024"></canvas>

And JS:

function updateVideo( ) {
    var canvas = document.getElementById( 'canvas' );
    var ctx = canvas.getContext( '2d' );
    var myVideo = document.getElementById( 'video' );
    ctx.drawImage( myVideo, 0, 0, 640, 480 );
}
setInterval ( updateVideo, 24 );

Solution 2

Here is simple CSS trick, you don't need to add any JavaScript or jQuery code. Use object-fit CSS property on video tag.

HTML

<video controls="controls" id="video">
<source src="sintel-trailer.ogv" type='video/ogg; codecs="theora, vorbis"'>
<source src="sintel-trailer.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</video>

CSS

#video{
  object-fit: initial;
  width: 400px;
  height: 300px;
}

See Fiddle

Share:
31,104
coder
Author by

coder

I'm a digital marketer as well as passionate about web designing.

Updated on January 26, 2020

Comments

  • coder
    coder over 4 years

    May be its a simple question but it's really driving me crazy. I just want to set the height and width of the HTML5 video.

    I am using this code:

     <video controls="controls" width="1000" id="video">
                <source src="sintel-trailer.ogv" type='video/ogg; codecs="theora, vorbis"'>
                <source src="sintel-trailer.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
      </video>
    

    Result: enter image description here

    If I add height attribute

    <video controls="controls" width="1000" height="300" id="video">
                    <source src="sintel-trailer.ogv" type='video/ogg; codecs="theora, vorbis"'>
                    <source src="sintel-trailer.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
     </video>
    

    Result: enter image description here

    So am I missing something here?

    Can anyone correct the mistake I'm doing.

  • Daniel Lizik
    Daniel Lizik about 8 years
    Never even heard of this property before, had been suffering through oddly positioned video for hours before finding this, thank you
  • S.Yadav
    S.Yadav over 6 years
    working for me, +1, i used objest-fit: cover, but this worked.
  • ehsan
    ehsan over 4 years
    i've used object-fit: contain; to solve my problem. but thanks for the hint.