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.
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)"
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");
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"
});
{}, and properties are separated by commas.
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). |
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"
});
});
"20px") or just numbers (20). jQuery will automatically append
px if you provide a raw number.
style
attribute.background-color) or
camelCased (backgroundColor) in jQuery.