jQuery css() Method – Get and Set Element Styles
The jQuery css() method allows you to retrieve or apply CSS properties to elements with minimal code. Whether you need to read computed styles, change a single property, update multiple styles at once, or compute values dynamically, css() method in jQuery provides a flexible API. In this tutorial, you’ll learn how to use css() in various scenarios effectively.
Key Uses of css()
- .css(propertyName): Get the value of a CSS property on the first matched element.
- .css(propertyName, value): Set a single CSS property for all matched elements.
- .css({prop1: val1, prop2: val2, …}): Set multiple CSS properties at once.
- .css(propertyName, function(index, currentValue){…}): Compute and set a property value per element.
Get a CSS Property with css() Method
Use css(propertyName) to read a computed style from the first element in the jQuery selection.
Get CSS Property
$(document).ready(function() {
$('#getCssBtn').click(function() {
const bgColor = $('#myBox').css('background-color');
$('#resultContainer').text('Background color: ' + bgColor);
});
});
Set a Single CSS Property
Use css(propertyName, value) to apply one style to all matched elements.
Set Single CSS Property
$(document).ready(function() {
$('#setBorderBtn').click(function() {
$('.item').css('background', '#4CAF5055');
$('.item').css('border', '4px solid #4CAF50');
});
});
Set Multiple CSS Properties at Once
Pass an object to css() to set several properties in one call.
Set Multiple CSS Properties
$(document).ready(function() {
$('#styleItemsBtn').click(function() {
$('.item').css({
'background-color': '#2196F3',
'border': '4px solid #0D47A1',
'box-shadow': '0 4px 12px rgba(0,0,0,0.3)'
});
});
});
Compute Styles with Function Callback
Provide a callback to css() method to calculate values per element based on its index or current value.
Dynamic CSS via Callback
$(document).ready(function() {
$('#growItemsBtn').click(function() {
$('.item').css('width', function(index, currentWidth) {
// Parse current width (strip 'px') and add 20px times the index
const cw = parseInt(currentWidth, 10);
return (cw + 20 * index) + 'px';
});
});
});
Remove Inline Styles by Clearing Values
You can remove an inline style by setting its value to an empty string.
Clear CSS Property
$(document).ready(function() {
$('#applyStyleBtn').click(function() {
// set an inline background color
$('#box').css('background-color', '#FFEB3B');
});
$('#clearStyleBtn').click(function() {
// remove the inline background-color
$('#box').css('background-color', '');
});
});