The .css()
method makes it super simple to find and set CSS properties and combined with other methods like .animate(), you can make some cool effects on your site.
In its simplest form, the .css()
method can set a single CSS property for a particular set of matched elements. You just pass the property and value as strings and the element’s CSS properties are changed.
$('.example').css('background-color', 'red');
This would set the ‘background-color’ property to ‘red’ for any element that had the class of ‘example’.
But you aren’t limited to just changing one property at a time. Sure, you could add a bunch of identical jQuery objects, each changing just one property at a time, but this is making several, unnecessary calls to the DOM and is a lot of repeated code.
Instead, you can pass the .css()
method a Javascript object that contains the properties and values as key/value pairs. This way, each property will then be set on the jQuery object all at once.
$('.example').css({
'background-color': 'red',
'border' : '1px solid red',
'color' : 'white',
'font-size': '32px',
'text-align' : 'center',
'display' : 'inline-block'
});
This will change all of these CSS properties on the ‘.example’ elements.