How to create a YouTube video background with CSS

文章推薦指數: 80 %
投票人數:10人

In this tutorial we will learn how to set a fullscreen Youtube video as a background using CSS and HTML. fullPage.js GetfullPage JavaScript WordPressTheme PluginElementor PluginGutenberg Extensions Contact HowtocreateaYouTubevideobackgroundwithCSS Jul12,2021 UsinganembeddedYouTubevideoasabackgroundisacommontechniqueinnowadayswebsites.YoucanusetheHTML5videotagtocreateabackgroundvideo.However,thatwouldmeanhostingavideoonlinesomewhere.AndIdon’tknowyou,butinmycase,Ialwaystrytoavoidthatoption.Youtubevideoembedsareagoodalternativetoself-hostedvideos.Theysavebandwidthandtheyloadsuperfast.But,sincetheyareinaniframe,theycanbeabitmoretrickytodealwith.Inthistutorial,we'llbegoingoverhowtocreateaYouTubevideobackgroundforourwebsite. GettingtheHTMLfortheembeddedYoutubevideo ThefirstthingwehavetodoisgrabbingtheembedcodeoftheYouTubevideothatwewanttodisplayinthebackground.Justgotoyourchosenvideoandclickonthe“share”button. Severaloptionswillpopup.Clickonthe“embed”one. Thiswillopenupanewboxonyourscreenwiththecodeforthevideoyouwanttoembed.Disablethe“Showplayercontrols”intheembedoptionsandthenclickonthe“copy”button. Nowcreateadivcontainerandpastethereyourembedcode. Wewillremovealltheunnecessaryproperties,whichareallexceptcontrols=0(thewidthandheightpropertiesalsohavetoberemoved)Finallywewilladdtwoextraproperties:autoplay=1andmute=1. Thefinalresultisavideo-containerdivthathasaniframewhichcontainsthesourceoftheYouTubevideo.Thisvideowillautoplayonmutewhenoneofourusersvisitsourwebpage. CenteringtheYouTubevideobackgroundwithCSS TomaketheiframeafullpageYouTubevideobackgroundwe'llbeapplyingsomeCSSpropertiestotheparentvideo-containeraswellastheiframe: .video-container{width:100vw;height:100vh;}iframe{position:absolute;top:50%;left:50%;width:100vw;height:100vh;transform:translate(-50%,-50%);} TheCSSpropertiesappliedontheparentcontainerscaleit100%ofthescreenviewport'sheightandwidth.Theiframewhichisinsideisalsoscaledto100%ofthescreenviewport'sheightandwidth. Theiframewillhaveanabsolutepositionthatwillallowustopositiontheiframeexactlywherewewantit.Inthiscase,it'splacedontopoftheparentcontainer.Thepositioningattributestopandleftareusedtosetthelocationoftheupperleftcorneroftheiframeinthecenterofthescreen. TogetourYouTubevideobackgroundcentered,weusetransformtoapplyanegativetopmarginofhalfthevideo'sheight,andanegativeleftmarginofhalfthevideo'swidth.Thiswilloffsettheiframerelativetotheelement(nottheparentcontainer)centeringtheYouTubevideobackgroundverticallyandhorizontally. Makingourvideofullscreen Asyoucanseenow,ourYouTubevideoisplacedinthecenterofthescreenbutithasnotbeenscaledtobethefullwidthofourwebsite.Todowesowillusetheaspect-ratiomediafeature: @media(min-aspect-ratio:16/9){.video-containeriframe{/*height=100*(9/16)=56.25*/height:56.25vw;}}@media(max-aspect-ratio:16/9){.video-containeriframe{/*width=100/(9/16)=177.777777*/width:177.78vh;}} Theaspectratioisthewidthtoheightratiooftheviewport.16:9denotesawidthof16unitsandaheightof9units.16:9isthestandardwidescreenaspectratiothatisusedontheweb.Generally,mostvideosareshotinthisaspectratio. The16:9aspectratiocorrespondsto56.25oftheviewport'sheightand177.78oftheviewport'swidth.Tocreatea16:9ratio,wemustdivide9by16(0.5625or56.25%).Thisallowsthebrowsertodeterminethevideo'sdimensionsbasedonthewidthofitsparentcontainer.ThiswillmaintaintheaspectratiooftheYoutubevideoasitscalestofitthebackgroundofthewebpage. Addingoverlaytextontopofourvideo ThetexttobedisplayedoverourbackgroundYoutubevideoisputinsideaseparatedivlikeso:

UseayoutubevideoasafullscreenbackgroundwithCSS

TheCSSisappliedonthetextdivtomoveitalongwithanyofitscontentsontopofthevideo: #text{position:absolute;color:#FFFFFF;left:50%;top:50%;transform:translate(-50%,-50%);} WehaveappliedthesameCSSpropertiesaswedidontheiframetocenterthetext-divinthecenterofourwebpage.You'llwanttomakesurethatthetextwhichisplacedontopofourYouTubevideobackgroundhashighcontrastsothatitcaneasilyberead. YoucanalsoplaceotherelementssuchashoverbuttonsandusethesameCSSpropertiestoplacethemontopofourYouTubevideobackground. AddingtheYoutubeembeddedloopoption Ifyouuseashortvideoyou'llnoticehowtherelatedvideosshowoncethevideoisfinished.Toavoidthiswehavetousealittletrick.Addingtheparameterloop=1tothesourceofthevideoisnolongerenough,wehavetoaddmoreparameterandthisistheplaylistonetowhichwewillassigntheIDoftheyoutubevideo. So,ifwehavethisvideoweshouldlookforitsid,whichisthecodeafterthe/embed/partorafter?v=whenaccessingthevideothroughtyoutube.Then,wesimplypasteitonourplaylistparam: &playlist=Yj2iELI6OeI&loop=1 Ourfinalembeddedvideoshoullooklikethis: Result Andhere'stheresult:abeautifullfull-screenvideousingYoutube! SeethePen onCodePen. Conclusion CreatingaYouTubevideobackgroundisoneofthesimplestsolutionstomakeadifferenceandstandoutfromyourwebcompetitors.Userswhoenteryourwebsitewillbeimmersedinauniquevisualexperiencethatwillnoteasilyforget. Thistechniquecanbequiteimpressivewithfull-screenvideosonwebsitesusingfullPage.js.Checkoutthisfullscreenvideosexample! NowthatyouhavelearnedhowtocreateaYouTubevideobackground,itisyourtimeto“showoff”!Ifyouplantostartabusiness,creatingalandingpagewithaYouTubevideobackgroundwouldbeaneasysolutionthatwillcauseatthesametimeagreatimpressiononyourpossiblecustomers.Sharewithusyourwebsiteswhenyoufinish.Wewouldlovetoseethem! Relatedarticles: HowtocreateavideobackgroundwithCSS HowtocreateafullscreenvideowithCSSandHTML reportthisad Join2,000+readersandlearnsomethingneweverymonth! Enteremailaddress Subscribe Getnotifiedaboutnewblogposts,tips,tricks,fullPage.jsnewsetc. RSSfeed WebDeveloper?CheckoutfullPage.jstomakebeautifulsites! CheckfullPage! xx



請為這篇文章評分?