jQuery CSS Property Manipulation — Complete Guide to .css()
In this tutorial, you will learn about jquery css property manipulation. We cover key concepts, practical examples, and best practices to help you master this topic.
jQuery .css() method reads and sets CSS properties on elements, bridging the gap between inline styles and computed styles with a consistent cross-browser API.
What You'll Learn
- Reading CSS property values with .css()
- Setting single and multiple CSS properties
- Using callback functions for dynamic values
- Working with CSS custom properties (variables)
- Understanding camelCase vs hyphenated property names
Why It Matters
Reading and writing CSS properties is fundamental to dynamic UI. The .css() method normalizes browser differences and provides a simple syntax for both reading computed values and setting inline styles.
Real-World Use
A color picker that updates an element's background-color as the user drags sliders, a resizable panel that reads its current width and adjusts margins accordingly, and a drag-to-highlight tool that sets position and dimensions dynamically.
CSS Read/Write Flow
flowchart LR
A[.css('property')] --> B[Get Computed Value]
A --> C[Get Inline Value]
D[.css('prop', 'val')] --> E[Set Inline Style]
D --> F[Override Stylesheet]
style D fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px
Reading CSS Properties
// Read a single property
var color = $('.box').css('color');
var width = $('.box').css('width');
console.log('Color:', color); // Output: rgb(255, 0, 0)
console.log('Width:', width); // Output: 200px
// Read from the first matched element only
var firstBg = $('.item').css('background-color');
// Reading shorthand properties
var background = $('.box').css('background');
// Note: shorthand may return different formats across browsers
Expected output: css() returns the computed value of the property, not the stylesheet value. Colors are normalized to rgb/rgba format. Dimensions include the unit.
Setting CSS Properties
// Set a single property
$('.box').css('background-color', '#3498db');
$('.box').css('font-size', '16px');
$('.box').css('margin-top', '20');
// Set multiple properties (object syntax)
$('.box').css({
'background-color': '#2ecc71',
'border': '2px solid #27ae60',
'border-radius': '8px',
'padding': '15px',
'color': '#fff'
});
// Without quotes for camelCase (preferred)
$('.box').css({
backgroundColor: '#e74c3c',
border: '1px solid #c0392b',
borderRadius: '4px'
});
Expected output: Inline styles are applied directly to the element, overriding any stylesheet values. The object syntax is recommended for setting multiple properties at once.
CSS Property Names: CamelCase vs Hyphenated
// Hyphenated (must be quoted in object syntax)
$('.box').css('background-color', 'blue');
// CamelCase (preferred for object syntax without quotes)
$('.box').css({
backgroundColor: 'blue',
fontSize: '14px', // font-size
marginLeft: '10px', // margin-left
borderTopWidth: '2px', // border-top-width
zIndex: 100 // z-index (stays the same)
});
// Vendor prefixes are handled by jQuery
$('.box').css({
WebkitTransition: 'all 0.3s', // -webkit-transition
MozTransition: 'all 0.3s', // -moz-transition
transition: 'all 0.3s'
});
Setting with Callback
// Alternating row colors
$('tr').css('background-color', function(index) {
return index % 2 === 0 ? '#f8f9fa' : '#ffffff';
});
// Incremental adjustments
$('.box').css('width', function(index, currentValue) {
// currentValue is the computed width (e.g., '200px')
var current = parseInt(currentValue, 10);
return (current + 50) + 'px';
});
// Toggle classes based on conditions
$('.item').css('display', function() {
return $(this).hasClass('hidden') ? 'none' : 'block';
});
Expected output: The callback receives the element index and the current CSS value. It should return the new value as a string.
CSS Custom Properties (Variables)
// Set CSS custom properties
$('.card').css('--card-primary', '#3498db');
$('.card').css('--card-radius', '12px');
$('.card').css({
'--card-bg': '#f8f9fa',
'--card-border': '#dee2e6'
});
// Read CSS custom properties
var primary = $('.card').css('--card-primary');
console.log(primary); // Output: #3498db
Working with Numeric Values
// parseInt extracts the numeric value
var width = parseInt($('.box').css('width'), 10);
console.log('Width in pixels:', width);
// parseFloat for decimal values
var opacity = parseFloat($('.box').css('opacity'));
console.log('Opacity:', opacity);
// Math operations
$('.box').css('width', function(i, val) {
return parseInt(val, 10) * 1.5 + 'px';
});
// .css('width') returns string like '200px'
// Use parseInt to get the number for calculations
CSS vs .css() for Transitions
// jQuery sets inline styles, which can trigger CSS transitions
// if the element has transition property set in stylesheet
// CSS:
// .box { transition: background-color 0.3s ease; }
// jQuery triggers the transition:
$('.box').css('background-color', '#e74c3c');
// The color changes smoothly over 0.3s
// Without CSS transitions, jQuery animations handle this
$('.box').animate({ backgroundColor: '#e74c3c' }, 300);
Common Mistakes
Getting vs setting confusion -
.css(property)returns the value (string)..css(property, value)returns the jQuery object (chainable)..css({...})also returns the jQuery object.Shorthand properties return different formats -
.css('background')may return different formats in different browsers. Read specific properties likebackground-colorinstead.Forgetting units - Numeric values without units are treated as px for most properties. For
fontSize,2means2px(too small). Always include units:'1.5em','14px'.Setting properties that affect layout - Changing width, height, margin, or padding triggers layout recalculations. Batch changes or use CSS classes to minimize reflows.
Opacity value range -
.css('opacity', val)accepts 0 to 1. Values outside this range are clamped. For IE8, jQuery uses a filter fallback.
Practice Questions
- What does .css('width') return?
- How do you set multiple CSS properties at once?
- What naming convention does jQuery use for CSS properties with hyphens?
- How do you use a function to determine a CSS value dynamically?
- What is the difference between reading and writing with .css()?
Challenge: Build a color mixer with three sliders (red, green, blue) that update an element's background-color in real time using .css(). Display the current RGB and hex values. Include an opacity slider.
FAQ
Mini Project
Build a live CSS editor where users can select an element and adjust its width, height, padding, margin, background color, border radius, and box shadow using sliders. Display the resulting CSS code in a textarea.
What's Next
CSS styles the appearance, but dimensions and position methods measure the actual space elements occupy on the page.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro