Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting multiple style.background values

Tags:

javascript

css

I want to use gradients in my background and to be cross-platform I would like to set background with vendor prefixes:

background: -webkit-linear-gradient(red, blue);
background: -o-linear-gradient(red, blue);
background: -moz-linear-gradient(red, blue);
background: linear-gradient(red, blue);

How can I set multiple style.background's on a HTMLElement, using Javascript to support the vendor prefixes?

Update: I wish not to use jQuery or any other external library.

like image 342
HischT Avatar asked Mar 07 '14 08:03

HischT


People also ask

How do I put multiple background colors in HTML?

CSS allows you to add multiple background images for an element, through the background-image property. The different background images are separated by commas, and the images are stacked on top of each other, where the first image is closest to the viewer.

How do you make a background with multiple colors in CSS?

Essentially, the background property can hold two contents one over the other: 2 gradients, 2 images or you can mix-and-match any of those. To use more than 2 colors (because why not), put the powerful rgba() to use and use 2 gradient parameters.

How do I stop my background image from repeating?

To make a background image not repeat in HTML, specify no-repeat in the background-repeat property or the background shorthand property. The background image is set to 'no-repeat' using the 'background-repeat' property. The above example uses the background-repeat property to set the image to no-repeat .


1 Answers

Another way is to set your props via the style attribute

 var styleText = '-webkit-linear-gradient(red, blue); ' +  
                 '-o-linear-gradient(red, blue); ' +
                'linear-gradient(red, blue);'

 el.setAttribute('style', styleText);

If you think you risk overriding any other styles already set inline you will want to get the current styles and then add the new ones on top:

var el = document.getElementById('myEl'),
    currentStyle = el.getAttribute('style'),
    styleText =  'background: -webkit-linear-gradient(top, red 0%,blue 100%); ' +  
                 'background: -o-linear-gradient(top, red 0%,blue 100%); ' +
                 'background: -ms-linear-gradient(top, red 0%,#blue 100%);' +
                 'background: linear-gradient(to bottom, red 0%, blue 100%);';


 el.setAttribute('style', currentStyle + styleText);

Here's a bin with an example.

like image 65
Aurelio Avatar answered Sep 19 '22 13:09

Aurelio