Multiple Background Images with background-clip, background-origin, and background-size - Exercise

Contact Us or call 1-877-932-8228
Multiple Background Images with background-clip, background-origin, and background-size - Exercise

Multiple Background Images with background-clip, background-origin, and background-size

Duration: 10 to 20 minutes.

In this exercise, you will

  1. Open ClassFiles/CssBackgroundTricks/Exercises/background-clip-origin-size/index.html in a text editor and in a browser.
  2. Note that the page holds a <div> with id bg; some of the styles for this <div> are already written for you in the <head> of the page.
  3. Style the #bg <div> to look like this: exercise screenshot
  4. Be sure to match the following features:
    1. A 10-pixel-wide, semitransparent, green border; use hsla to specify color
    2. The boardwalk.jpg background image fully covers the <div>, extending right up to the edge of the border of the element
    3. A second background image (grass.jpg) fill the width (but not the height) of the content area of the <div>

Solution:

CssBackgroundTricks/Solutions/background-clip-origin-size/index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>CSS3 Background Clip, Origin, Size</title>
	<style type="text/css">
		#bg {
			margin:auto;
			width:200px;
			height:150px;
			padding:20px 20px 200px 20px;
			border:20px solid hsla(90,100%,20%,0.5);
			background-image:url(grass.jpg), url(boardwalk.jpg);
			background-clip:content-box, border-box;
			background-origin: padding-box, border-box;
			background-size:100% auto, cover;
			background-repeat:no-repeat;
			text-align: center;
			color:#fff;
		}
	</style>
</head>
<body>
	<div id="main">
		<h1>CSS3 Background Clip, Origin, Size</h1>
		<div id="bg">
			This element has two background images
		</div>
	</div>
</body>
</html>

Code Explanation

We specify two background images; grass.jpg is listed first and, thus, sits on top of boardwalk.jpg.

We set the background painting area for each background image with a comma-separated pair of values for background-clip. grass.jpg gets a value of content-box and thus fills behind the text only; boardwalk.jpg gets a value of border-box and thus extends under the semitransparent border. Similarly, we set two values for background-origin to position the background images as specified.

Last, we set the size of the background images with background-size. grass.jpg is asked to fill the width of the space allocated to it (with a value of 100% auto) and boardwalk.jpg is asked to cover the whole element.

Next