UnDefined

Jonahlyn's Personal Blog

Dabbling With CSS3 Backgrounds and Gradients

| Comments

A few weeks ago I was trying to figure out how to create a thin, vertical line using CSS the purpose of which was to separate two sections of a web page, for instance a side bar from main content, that would be offset a number of pixels from the top of the element. I couldn’t use a border because of the offset needed (I don’t think) and modifying the underlying HTML was out.

Reading this 24ways article on CSS3 patterns helped me to understand css3 gradients and multiple backgrounds a little better and gave me some ideas on how I might accomplish this using CSS3.

Multiple backgrounds are applied in layers so the top-most background will cover the backgrounds underneath it. I found it helpful to create the backgrounds separately and then combine them together in the end.

I started with creating a 4 pixel wide, solid grey, vertical line at the 240 pixel mark. This would be my bottom-most background layer.

1
2
3
4
5
background-color: #fff;
background-image:
  linear-gradient(0deg, transparent 240px, #5e5d60 240px, #5e5d60 244px, transparent 244px, transparent);
background-size: 100%;
min-height: 100%;

Next, I created a series of 1 pixel high horizontal lines alternating white and transparent. The 2 pixel height specified in “background-size” accommodates 2 lines and all of this repeats vertically to create multiple lines. Note the background color was changed so the transparent lines could be seen.

1
2
3
4
5
background-color: #5e5d60;
background-image:
  linear-gradient(top, #fff 1px, transparent 1px);
background-size: 100% 2px;
min-height: 100%;

For the offset I created a solid white block covering the top 70 pixels with the remainder being transparent. The background color here was also changed so the white block could be seen.

1
2
3
4
5
background-color: #5e5d60;
background-image:
  linear-gradient(top, #fff 70px, transparent 70px);
background-size: 100%;
min-height: 100%;

And finally combining all the backgrounds together produces the separator line:

1
2
3
4
5
6
7
background-color: #fff;
background-image:
  linear-gradient(top, #fff 70px, transparent 70px),
  linear-gradient(top, #fff 1px, transparent 1px),
  linear-gradient(0deg, transparent 240px, #5e5d60 240px, #5e5d60 244px, transparent 244px, transparent);
background-size: 100%, 100% 2px, 100%;
min-height: 100%;

Not very exciting compared to the other CSS3 backround patterns that have been coming out lately but cool enough considering a few weeks ago I didn’t think it was possible to do without creating an image.

There is (of course) a problem that makes this unusable for me. The line refuses to appear in certain versions of Chrome unless the thickness of the line is 4 pixels or wider. I needed the line to be thinner. Oh well. Back to the drawing board.

Comments