HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery css() Method

The css() method is the most direct way to manipulate the look of an HTML element. It allows you to either "get" the current computed style of an element or "set" one or more CSS properties directly through the style attribute.


1. Returning a CSS Property

To read a CSS property value, simply pass the name of the property as a string. jQuery will return the computed value (the final value used by the browser).

// GETting the background color
var color = $("p").css("background-color");

// Example result: "rgb(255, 255, 255)"

2. Setting a Single CSS Property

To change one style, pass the property name followed by the new value.

// SETting the color to red
$("p").css("color", "red");

// SETting the font size
$("h1").css("font-size", "34px");

3. Setting Multiple CSS Properties

To change several styles at once, pass an **object** containing the property-value pairs. This is much more efficient than calling css() multiple times.

$("p").css({
    "background-color": "yellow",
    "color": "#333",
    "font-size": "200%",
    "padding": "20px"
});
Syntax Tip: When setting multiple properties, the entire list goes inside curly braces {}, and properties are separated by commas.

When to use css() vs. Classes

Choosing the right tool is key to professional development:

Method Best Used For...
addClass() Static designs, themes, and pre-defined visual states.
css() Values that change constantly (e.g., mouse positions, window size, calculated math).

Practical Example: Tracking Mouse Position

Here is a classic use case for the css() method: following the user's mouse cursor with an element.

$(document).mousemove(function(event) {
    $("#follower").css({
        "left": event.pageX + "px",
        "top": event.pageY + "px"
    });
});
Pro Tip: Most numeric values (like pixels) can be passed as strings ("20px") or just numbers (20). jQuery will automatically append px if you provide a raw number.

Key Points to Remember

  • The css() method manipulates the inline style attribute.
  • Get Mode: Pass one argument (string).
  • Set Mode (Single): Pass two arguments (string, value).
  • Set Mode (Multiple): Pass one argument (object).
  • Property names can be either hyphenated (background-color) or camelCased (backgroundColor) in jQuery.