Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background gradient color and background image DRYly

Tags:

html

css

I have a number of headings and in the background of each I want to show the same gradient color, but a different (non-repeating) background image. I want to avoid duplicating any CSS rules for the background gradient color or background image position, because they will be the same for each heading. In other words, the only thing I should need to specify for an individual heading is the path to the background image file.

Here's what I have at the moment:

<h1 class="banner bgImage img1">background image 1</h1>
<h1 class="banner bgImage img2">background image 2</h1>
<h1 class="banner bgImage img3">background image 3</h1>
<h1 class="banner">heading without background image</h1>

.banner {
    /* For old browsers that don't support gradients */
    background-color: #9FCC1D; 

    /* browser-specific prefixes omitted */
    background-image: linear-gradient(#75A319, #9FCC1D); 
    padding: 7px 7px 7px 15px;
}

/* Specifies position of background image */
.bgImage {
    background-position: 5px 50%, 0 0;
    background-repeat: no-repeat;
    padding-left: 30px;
}

.img1 {
    background-image: url(img1.png"), linear-gradient(#75A319, #9FCC1D);
}

.img2 {
    background-image: url(img2.png"), linear-gradient(#75A319, #9FCC1D);
}

.img3 {
    background-image: url(img3.png"), linear-gradient(#75A319, #9FCC1D);
}

There are a couple of problems with this

  1. I have to repeat the linear-gradient style in each .imgX rule
  2. It doesn't render correctly in Chrome, which doesn't seem to support a comma-separated list of background-image and background-repeat properties. This is what gets displayed in Chrome

enter image description here

How can I fix the problem with the way the background is rendered in Chrome while minimising duplication of CSS rules?

like image 351
Dónal Avatar asked Feb 24 '12 17:02

Dónal


2 Answers

Use the :before pseudo-class for your background icons.

.img1:before {
  content: '';
  float: left;
  position: relative;
  background: transparent url('img1.png') left top no-repeat;
  width: 16px; /* change to actual width of img */
  height: 16px; /* change to actual height of img */
}

Or, since you're trying to relieve the amount of CSS, you can specify a class for the gradient and append that in your HTML.

like image 133
Nick Beranek Avatar answered Nov 09 '22 09:11

Nick Beranek


Don, you have two classes which this background gradient can be applied to, bgImage and banner. Simply apply your gradient on to one of those classes and go from there. Also append repeat-x right after your image url to ensure it will repeat across.

like image 4
Robert Guilfoyle Avatar answered Nov 09 '22 10:11

Robert Guilfoyle