Hayden Hayden - 5 months ago 22
CSS Question

Cannot set background-image to repeating-linear-gradient in code behind

In my code, I want to add a repeating-linear-gradient to my

div
from my code behind. At the moment, I am trying to set this by the following code:

_div.Style.Add("background-image", "repeating-linear-gradient(90deg,rgba(0,100,200,.5),rgba(0,100,200,.5) 1px,transparent 1px,transparent 1px,rgba(0,100,200,.5) 1px)");


But the code has no effect on the div itself. I have been able to change the
display
with similar code:

_div.Style.Add("display", "inherit");


Any help would be appreciated.

Edit

Here is the
HTML
for the
div


<div id="_div" runat="server">
<asp:Label ID="_Label" runat="server"></asp:Label>
</div>


Here is the
CSS
for the
div


#output_div {
display: none;
padding-top: 2%;
padding-bottom: 2%;
width: 50%;
margin: 0 auto;

/*Below line works, but would like to set it dynamically on the server side*/
/* background-image: repeating-linear-gradient(90deg, rgba(0,100,200,.3), rgba(0,100,200,.3) 1px, transparent 1px, transparent 1px, rgba(0,100,200,.3) 1px);*/

background-size: 4px 4px;
}

Answer

Give it a try with following approach,

_div.Attributes.Add("style", "background-image: repeating-linear-gradient(90deg,rgba(0,100,200,.5),rgba(0,100,200,.5) 1px,transparent 1px,transparent 1px,rgba(0,100,200,.5) 1px)");

That way, style attribute will be rendered to the output HTML.

Update You can also try adding a specific CSS class.

.myBackgroundImg {
    background-image: repeating-linear-gradient(90deg, rgba(0,100,200,.3), rgba(0,100,200,.3) 1px, transparent 1px, transparent 1px, rgba(0,100,200,.3) 1px);
}

Then you can apply it in the code behind.

 _div.Attributes.Add("class", "myBackgroundImg");
Comments