How to Get and Set CSS Properties Using jQuery: A Complete Guide

Last updated 1 week ago | 19 views 75     5

Tags:- JQuery

Introduction: Why Manipulate CSS with jQuery?

Modern websites need to respond dynamically to user interactions—like highlighting a field on focus, showing or hiding sections, or updating layout elements in real time. While CSS handles static design, jQuery lets you modify styles dynamically using JavaScript.

The primary jQuery method for working with inline styles is .css(), which allows you to both get and set CSS properties directly on elements. This simplifies style manipulation without needing to create or switch between classes manually.


jQuery .css() Method Overview

The .css() method in jQuery is a powerful utility for:

  • Getting the current value of a CSS property

  • Setting one or more CSS properties on selected elements

✅ Syntax

// Get a CSS property
$(selector).css('propertyName');

// Set a single CSS property
$(selector).css('propertyName', 'value');

// Set multiple CSS properties
$(selector).css({
  property1: 'value1',
  property2: 'value2'
});

Step-by-Step Usage with Examples

1. Get a CSS Property

let bgColor = $('#box').css('background-color');
console.log(bgColor); // e.g., "rgb(255, 255, 255)"

Retrieves the current background color of the element with id="box".


2. Set a Single CSS Property

$('#box').css('background-color', 'lightblue');

Sets the background color of #box to light blue.


3. Set Multiple CSS Properties

$('#box').css({
  'color': 'white',
  'font-size': '18px',
  'padding': '20px'
});

Applies multiple inline CSS styles in one call.


4. Set Properties Based on Function

You can also use a function to calculate the value dynamically.

$('.item').css('font-size', function(index, value) {
  return parseFloat(value) + 2 + 'px';
});

Increases the font size of each .item by 2 pixels, based on its current value.


Common CSS Property Names in jQuery

CSS Property jQuery Equivalent (camelCase)
background-color 'backgroundColor'
font-size 'fontSize'
border-radius 'borderRadius'
z-index 'zIndex'

Hyphenated CSS properties are written in camelCase in jQuery.


✅ Complete Functional Code Example

<!DOCTYPE html>
<html>
<head>
  <title>jQuery CSS Properties Demo</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    #box {
      width: 200px;
      height: 100px;
      background-color: lightgray;
      color: black;
      text-align: center;
      line-height: 100px;
      margin: 20px;
    }
  </style>
</head>
<body>

<div id="box">Hello, jQuery!</div>

<button id="changeStyle">Change Style</button>
<button id="readStyle">Read Style</button>

<script>
  $('#changeStyle').click(function() {
    $('#box').css({
      'background-color': '#4CAF50',
      'color': 'white',
      'font-size': '20px',
      'border-radius': '10px'
    });
  });

  $('#readStyle').click(function() {
    let bg = $('#box').css('background-color');
    let fontSize = $('#box').css('font-size');
    alert(`Background: ${bg}\nFont Size: ${fontSize}`);
  });
</script>

</body>
</html>

This interactive example lets users change and read styles from the DOM using jQuery.


⚠️ Tips & Common Pitfalls

✅ Best Practices

  • Use multiple property objects to avoid repetitive .css() calls.

  • When changing styles frequently, consider toggling classes instead for better maintainability.

  • Always use camelCase for property names in jQuery (e.g., fontSize, backgroundColor).

❌ Common Mistakes

  • Using hyphenated property names (e.g., font-size) instead of camelCase (fontSize).

  • Expecting .css() to return styles set via external stylesheets—it only returns computed styles.

  • Relying solely on inline styles instead of CSS classes for responsive design or maintainable code.


jQuery .css() Usage Summary Table

Use Case Example Notes
Get property value $('#el').css('color') Returns computed value
Set a single property $('#el').css('color', 'red') Adds inline style
Set multiple properties $('#el').css({...}) More efficient
Use function for dynamic styling $('#el').css('width', function...) Great for responsive adjustments

Conclusion: Control CSS in Real-Time with jQuery

The .css() method in jQuery is a powerful and flexible tool for controlling how your web page looks and feels—dynamically. Whether you're building an interactive UI or reacting to user behavior, knowing how to get and set CSS properties allows you to:

  • Create more responsive and engaging designs

  • Modify styles based on logic or events

  • Keep your JavaScript clean and readable

Quick Takeaways:

  • Use .css() to manipulate inline styles on the fly

  • Always write properties in camelCase

  • Use multiple properties at once to simplify your code

  • Prefer CSS classes for complex styling scenarios