Harshit
Harshit

Reputation: 63

how to set html5 video tag source from css

Anyone with html css expertise help me out with this simple problem that I am unable to solve.

Basically, my html page has a video element which has a src attribute attached to it.

Now, what i want to do is, remove this src attribute from the video element and put this source in the css class of that video element.

So, how can I set the src of the video element from css?

I have tried using url,content attributes but it does not seem to work.
Or maybe i am doing it wrong. i would be grateful to anyone who could provide any input for this or share a small code which would use css to set the source of an html5 video element. please help me. Thank you.

Upvotes: 2

Views: 6879

Answers (2)

Joseph
Joseph

Reputation: 11

I did it with CSS using the display set to none or block, so that the video ("sample.mp4" or "sample2.mp3" is played depending on whether the user is on his laptop or on his mobile.

HTML:

<video id='video'>
    <source src="sample.mp4" type="video/mp4">
    Your browser does not support HTML5 video.
</video>
<video id='video2'>
    <source src="sample2.mp4" type="video/mp4">
    Your browser does not support HTML5 video.
</video>

CSS:

#video2 {display:none;}

@media only screen and (max-width: 500px) {
    #video2 {display:block;}
    #video {display:none;}
}

Upvotes: 1

Aditya Male
Aditya Male

Reputation: 266

You cannot set the video source via CSS. Because you see below the basic structure of video:

<video>
  <source src="sample.mp4" type="video/mp4">
  <source src="sample.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

You can set other attributes like background image, color, etc. However, you cannot set the source via css, which is used to design the play button & any other button functions. If you really need to do this without using <source src="sample.mp4" type="video/mp4"></source>, you will have to use JavaScript.

Upvotes: 1

Related Questions