This post explains how to use an image as a background for a section of a web page as shown in the following image. The webpage itself is from a course on Responsive Web Design by Jonas Schmedtmann that you can read about at www.webdesigncourse.co.
In the html there is no reference to the image, which is the background to the header element in the body of the page. The image background is controlled through the style.css file linked in the head.
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="vendors/css/normalize.css"> <link rel="stylesheet" type="text/css" href="vendors/css/grid.css"> <link rel="stylesheet" type="text/css" href="resources/css/style.css"> <link rel="stylesheet" type="text/css" href="vendors/css/ionicons.min.css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:100,300,300i,400"> <title>Omnifood</title> </head> <body> <header> <nav> <div class="row"> <img src="resources/img/logo-white.png" alt="Omnifood Logo" class="logo"> <ul class="main-nav"> <li><a href="#">Food delivery</a></li> <li><a href="#">How it works</a></li> <li><a href="#">Our cities</a></li> <li><a href="#">Sign up</a></li> </ul> </div> </nav> <div class="hero-text-box"> <h1>Goodbye junk food.<br/>Hello super healthy meals.</h1> <a class="btn btn-full" href="#">I'm hungry</a> <a class="btn btn-ghost" href="#">Show me more</a> </div> </header>
In the style.css file shown below we have the rule for the header element. Things to note:
- The header has two backgrounds: One background is a linear gradient that uses black with 70% transparency. This is not really a gradient, since we are only using one color. The purpose of this background is to make the image darker through transparency. This creates the sharp contrast between the background and the white font. The second background is the image.
- The background covers the entire width of the browser through the background-size property as explained here: http://www.w3schools.com/cssref/css3_pr_background-size.asp
- The image is centered
- The height of the header is the size of the browser view port. The size is defined in relative length as explained here: http://www.w3schools.com/cssref/css_units.asp
header{ background-image: linear-gradient(rgba(0, 0, 0, 0.7),rgba(0, 0, 0, 0.7)), url(img/hero.jpg); background-size: cover; background-position: center; height: 100vh; }