CSS3 Gradient Backgrounds and Controlling Their Height

Let’s assume you want to create a gradient background that starts at the top of the page and finishes at the bottom of your page header, i.e. is 100px tall. You can do this with a combination of CSS3 rules and avoid those ugly background images.

First off, I’m going to use the excellent Colorzilla gradient creator to establish the colors.

div#gradientbg { /*the following rules are from colorzilla*/
background: #e6f0a3; /* old browsers */
background: -moz-linear-gradient(top, #e6f0a3 0%, #d2e638 50%, #c3d825 51%, #FFFFFF 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#e6f0a3), color-stop(50%,#d2e638), color-stop(51%,#c3d825), color-stop(100%,#FFFFFF); /* webkit */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e6f0a3', endColorstr='#dbf043',GradientType=1 ); /* ie */
}

This works great for applying a background to the entire page. But we want to limit this to just the header. We’ll need two declarations. First a browser-specific rule (background-size). This, however could cause a series of gradient bands to tile across the screen. so simply add the no-repeat as well.

-moz-background-size:100% 100px;
...
background:no-repeat;

Final CSS

div#gradientbg { 
  display:block; width:500px; height:400px; border:1px solid #ccc;
  /*the following rules are from colorzilla*/
  
  background: #e6f0a3; /* old browsers */
  
  background: no-repeat -moz-linear-gradient(top, #e6f0a3 0%, #d2e638 50%, #c3d825 51%, #FFFFFF 100%); 
  -moz-background-size:100% 100px;/* firefox */
  
  background:  no-repeat -webkit-gradient(linear, left top, left bottom, color-stop(0%,#e6f0a3), color-stop(50%,#d2e638), 
  color-stop(51%,#c3d825), color-stop(100%,#FFFFFF)); 
  -webkit-background-size:100% 100px;/* webkit */
  
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#e6f0a3', endColorstr='#FFFFFF',GradientType=0 ); /* ie */
}

View the example page


Posted

in

, , , , , ,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *