jQuery css() Method
This method sets/returns one or more style properties for the specified elements.
Syntax:
- Return a CSS property:
$(selector).css("propertyname");
- Set a CSS property:
$(selector).css("propertyname", "value");
Example 1: In this example, background image is set by the background-image property using jQuery .css() method..
html
<!DOCTYPE html> < html > < head > < title > Setting background-image using JQuery CSS property </ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" > </ script > < style > body { text-align: center; } #div { width: 400px; height: 250px; } </ style > </ head > < body > < div id = "div" > < h1 >w3wiki</ h1 > < p >This is text of div box</ p > < br > < button >Click Here</ button > </ div > < script > $('button').on('click', function () { $('#div').css('background-image', 'url(' + 'https://media.w3wiki.org/wp-content/uploads/20190515121004/gfgbg1.png' + ')' ); }); </ script > </ body > </ html > |
Output:
Example 2: In this example, background image and background-repeat properties are set by the background property using JQuery css() method.
html
<!DOCTYPE html> < html > < head > < title > Setting background-image using jQuery css() Method </ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js" > </ script > < style > body { text-align: center; } #div { width: 500px; height: 350px; } </ style > </ head > < body > < div id = "div" > < h1 >w3wiki</ h1 > < p >This is text of div box</ p > < br > < button >Click Here</ button > </ div > < script > $('button').on('click', function() { $('#div').css('background', 'url(' + 'https://media.w3wiki.org/wp-content/uploads/20190515121004/gfgbg1.png) no-repeat' ); }); </ script > </ body > </ html > |
Output:
How to Set background Image using jQuery css() Method ?
This article will show you how to set the background image using jQuery. To set the background image, we are using the jQuery css() method.