Jerome
Jerome

Reputation: 6217

CSS paramtetrized sliding background with gradient composed inline and in css file

The following HTML tag is rendering as expected statically.

style='background: linear-gradient(to right, rgba(255,255,255,0) 20%, rgba(255,255,255,1) 30%, rgba(255,255,255,1)), url(<%= image_path "/bg/#{@this_area.id}.svg" %>);'>

However, as this is being dynamically managed by a variable, and the goal is to add

@keyframes moveBg {
    to {
        background-position: 100% 0;
    }
}

I was attempting to do the following

<div class='bg_x' style='background: url(<%= image_path "/bg/#{@this_area.id}.svg" %>);'>

and define the class

.bg_x {
  background: linear-gradient(to right, rgba(255,255,255,0) 20%, rgba(255,255,255,1) 30%, rgba(255,255,255,1))
  animation: moveBg 20s linear infinite;
}

However using a class plus an inline definition fails to integrate the gradient with the background image (even before adding the animation). So the inline is overriding the class, even though the instructions are complimentary.

As the CSS file cannot take variables, can this desired effect be achieved partially not inline?

Upvotes: 0

Views: 34

Answers (1)

Arno Tenkink
Arno Tenkink

Reputation: 1528

Because of the Cascading in CSS the inline indeed overrules the class. Never the less. linear gradients are a part of the background-image property (shorthand background if you want to combine multiple styles, just like margin-left and margin). Normally you can separate the background-color and background-image or other elements, but with linear-gradient() that isn't possible because they both use background-image property too bad.

In the example below you can find two solution that I found. Hopefully this helps you progress this issue.

/* ClassBased */
.bg_classBased {
  position: relative;
}

.bg_classBased:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  background: linear-gradient(to right, rgba(255,255,255,0) 20%, rgba(255,255,255,1) 30%, rgba(255,255,255,1));
  width: 100%;
  height: 100%;
}

/* Animation */
.bg_x {
  animation: moveBg 20s linear infinite;
}

@keyframes moveBg {
    to {
        background-position: 100% 0;
    }
}

/* misc styling */
div {
  padding: 40px;
}
<h1>Inline based</h1>
<div class="bg_x" style='background: linear-gradient(to right, rgba(255,255,255,0) 20%, rgba(255,255,255,1) 30%, rgba(255,255,255,1)), url("https://placehold.it/100x100");'></div>

<h1>Classbased</h1>
<div class="bg_x bg_classBased" style='background: url("https://placehold.it/100x100");'></div>

Upvotes: 1

Related Questions