jQuery css() Method
.css() reads and writes style properties. As a getter it returns the computed value — the final value after all stylesheets, inline styles and inheritance are applied. As a setter it writes an inline style on every matched element.
Syntax overview
| Call | Meaning |
|---|---|
.css("color") |
Get the computed value from the first element |
.css(["width", "color"]) |
Get several values as an object |
.css("color", "red") |
Set one property on all elements |
.css({ color: "red", fontSize: 18 }) |
Set several properties |
.css("width", "+=20") |
Relative change |
.css("color", "") |
Remove the inline value (stylesheet rules apply again) |
.css("left", function (i, old) { … }) |
Compute a value per element |
Getting computed values
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
.box { width: 150px; padding: 10px; background: rgb(7, 105, 173); color: white; font-size: 1.25em; }
</style>
</head>
<body>
<div class="box" id="b">Styled by the stylesheet</div>
<button id="read">Read styles</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$("#read").on("click", function () {
const $b = $("#b");
console.log("background-color:", $b.css("background-color"));
console.log("backgroundColor:", $b.css("backgroundColor")); // camelCase works too
console.log("font-size:", $b.css("font-size")); // em resolved to px
console.log("several:", $b.css(["width", "padding-left", "display"]));
});
</script>
</body>
</html>Notice the formats: colours come back as rgb(…), sizes as pixel strings ("20px") even if the stylesheet used em or %. Use parseFloat($el.css("font-size")) to get a number.
Setting styles
When setting, you can write hyphenated names in quotes or camelCase names. Plain numbers get "px" added automatically for properties that need a unit (but not for unitless properties such as opacity, zIndex, lineHeight or fontWeight).
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; }
#panel { width: 200px; padding: 10px; background: #eee; border: 1px solid #aaa; }
</style>
</head>
<body>
<button id="one">One property</button>
<button id="many">Many properties</button>
<button id="grow">Width +=30</button>
<button id="reset">Reset inline styles</button>
<div id="panel">Style me!</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const $p = $("#panel");
const log = () => console.log("style attribute:", $p.attr("style") || "(none)");
$("#one").on("click", () => { $p.css("background-color", "gold"); log(); });
$("#many").on("click", () => {
$p.css({
color: "white",
backgroundColor: "#0769ad",
borderRadius: 12, // → 12px
fontWeight: 700, // unitless, stays 700
opacity: 0.9
});
log();
});
$("#grow").on("click", () => { $p.css("width", "+=30"); log(); });
$("#reset").on("click", () => { $p.attr("style", ""); log(); });
</script>
</body>
</html>Note:
.css()writes inline styles, which beat almost every stylesheet rule. To remove a single inline value, set it to an empty string:.css("color", ""). Do not use.css("color", null)— use"".
Computing styles from data
.css() shines when values come from calculations, like a progress bar or a chart. CSS custom properties (variables) can also be set with .css("--name", value):
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; --accent: #0769ad; }
.row { display: flex; align-items: center; margin: 4px 0; font-size: 13px; }
.row span { width: 70px; }
.bar { height: 18px; background: var(--accent); border-radius: 3px; width: 0; transition: width .4s; }
</style>
</head>
<body>
<div id="chart"></div>
<button id="shuffle">New data</button>
<button id="color">Change accent</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
const langs = ["HTML", "CSS", "JS", "jQuery"];
const $chart = $("#chart");
langs.forEach(name => {
$chart.append($("<div class='row'>").append($("<span>").text(name), $("<div class='bar'>")));
});
function draw() {
const values = langs.map(() => Math.round(10 + Math.random() * 90));
$chart.find(".bar").css("width", function (i) {
return values[i] * 2; // px
});
console.log("values:", values);
}
draw();
$("#shuffle").on("click", draw);
const colors = ["#0769ad", "#e67e22", "#16a085", "#8e44ad"];
let k = 0;
$("#color").on("click", function () {
k = (k + 1) % colors.length;
$("body").css("--accent", colors[k]);
console.log("--accent:", $("body").css("--accent"));
});
</script>
</body>
</html>Vendor prefixes and special cases
- jQuery automatically adds vendor prefixes when a browser needs them (rare today).
- Shorthand properties such as
marginorborderare not reliably readable; readmarginTop,borderTopWidth, etc. individually. - For sizes, prefer the dedicated methods
.width(),.height(),.outerWidth()— they return numbers and handlebox-sizing(see the Dimensions lesson).
| Need | Prefer |
|---|---|
| Change the look for a state | .addClass() / .toggleClass() |
| A computed value (position, size, percentage) | .css() |
| A theme value used in many places | .css("--var", value) |
| Element size as a number | .width(), .height() |
Test yourself
What does $("#b").css("font-size") return if the stylesheet sets font-size: 1.25em and the parent is 16px?
"1.25em""20px"20undefined
How do you remove an inline color set earlier with .css()?
.css("color", "").css("color", false).removeCss("color").css("-color")
.css({ zIndex: 5, width: 100 }) sets which values?
z-index: 5px; width: 100pxz-index: 5; width: 100pxz-index: 5; width: 100- Nothing — values must be strings