Reading a style
.css("property") returns the computed style of the first selected element: the final value after every stylesheet, inline style and inherited value has been applied.
<style>
.card { padding: 12px; color: #1e3a8a; border: 3px solid #93c5fd; }
</style>
<div class="card" style="width: 200px">A card</div>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
const $card = $(".card");
console.log("color:", $card.css("color"));
console.log("padding-top:", $card.css("padding-top"));
console.log("width:", $card.css("width"));
console.log("border-top-width:", $card.css("borderTopWidth"));
console.log("display:", $card.css("display"));
</script>color: rgb(30, 58, 138)
padding-top: 12px
width: 200px
border-top-width: 3px
display: blockA few things to notice:
- Colours come back in
rgb()form, whatever format you wrote in the CSS. - Sizes come back in pixels as strings, such as
"12px". UseparseFloat()to turn them into numbers. - Property names can be written CSS-style (
"border-top-width") or JavaScript-style ("borderTopWidth"). - Read individual properties such as
padding-toprather than shorthands such aspadding, which browsers may not report consistently.
Setting styles
.css("property", value) writes an inline style (the style attribute) on every selected element. Pass an object to set several at once:
<p id="note">Remember to save your work.</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#note").css("color", "darkgreen");
$("#note").css({
backgroundColor: "#ecfdf5",
padding: "8px 12px",
"border-left": "4px solid #10b981"
});
console.log($("#note").attr("style"));
</script>color: darkgreen; background-color: rgb(236, 253, 245); padding: 8px 12px; border-left: 4px solid rgb(16, 185, 129);In an object, use camelCase names (backgroundColor) or quote the hyphenated name ("border-left").
Units and jQuery 4
If you pass a plain number, jQuery adds px for you, but in jQuery 4 only for a fixed set of properties: width and height (and their min-/max- versions), margin and padding (and their sides), border widths, and top, right, bottom, left. For any other property, a bare number is passed through as it is:
<p id="t">Sample text</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#t").css({ width: 300, padding: 6, marginLeft: 10 });
$("#t").css("font-size", 20); // no unit added in jQuery 4: ignored
$("#t").css("line-height", 1.5); // unitless is valid for line-height
$("#t").css("opacity", 0.8); // unitless by definition
console.log($("#t").attr("style"));
$("#t").css("font-size", "20px"); // write the unit
console.log("font-size now:", $("#t").css("font-size"));
</script>width: 300px; padding: 6px; margin-left: 10px; line-height: 1.5; opacity: 0.8;
font-size now: 20pxfont-size: 20 is not valid CSS, so the browser rejected it and no font size appears in the style attribute. Older jQuery versions quietly added px to almost every number, so code like this worked in jQuery 3 and silently stops working after an upgrade. The safe habit: always write the unit unless the property is meant to be unitless (opacity, z-index, line-height, flex-grow).
Relative values
A string starting with += or -= changes a value relative to its current one:
<div id="bar" style="width: 100px; height: 20px; background: #f59e0b"></div>
<button id="grow">Grow</button>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#grow").on("click", function () {
$("#bar").css("width", "+=40");
console.log("width:", $("#bar").css("width"));
});
</script>width: 140px
width: 180pxTwo clicks: 100px, then 140px, then 180px.
Removing an inline style
Set the property to an empty string. The inline value disappears and the stylesheet applies again:
<style> p { color: navy; } </style>
<p id="p" style="color: red">Text</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
console.log("before:", $("#p").css("color"));
$("#p").css("color", "");
console.log("after:", $("#p").css("color"), "| style attribute:", JSON.stringify($("#p").attr("style")));
</script>before: rgb(255, 0, 0)
after: rgb(0, 0, 128) | style attribute: "".css() or a class?
Inline styles are the strongest CSS rules apart from !important, so a value set with .css() overrides your stylesheet and is hard to change later. Use .css() for values that are truly calculated at run time, such as a width from a slider, the position of a tooltip, or a colour chosen by the user. For states such as error, active, open or hidden, toggle a class (previous lesson).
Reading several values at once
Pass an array of names to get an object back:
<div id="box" style="width: 120px; height: 60px; opacity: 0.5"></div>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
const styles = $("#box").css(["width", "height", "opacity"]);
console.log(JSON.stringify(styles));
</script>{"width":"120px","height":"60px","opacity":"0.5"}Common mistakes
- Leaving off units for properties such as
font-size,gaporletter-spacingin jQuery 4. - Comparing colours as written:
$(el).css("color") === "red"is false, because the browser returnsrgb(255, 0, 0). - Doing maths on strings:
"12px" + 4is"12px4". UseparseFloat()first. - Using
.css()for states and then fighting your own inline styles.
Exercise
Add an input type="range" from 10 to 40 and a paragraph. As the slider moves, set the paragraph's font size to the slider value in pixels.
Show one possible answer
<input id="size" type="range" min="10" max="40" value="16">
<p id="sample">Resize me</p>
<script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
<script>
$("#size").on("input", function () {
$("#sample").css("font-size", $(this).val() + "px");
console.log($("#sample").css("font-size"));
});
</script>The value from .val() is a string such as "12", so add "px" to make it a valid size.
Key points
- .css("prop") reads the computed style of the first element, the value the browser actually uses.
- .css("prop", value) and .css({ ... }) set inline styles on every selected element.
- jQuery 4 adds px to plain numbers only for sizes, margins, padding, border widths and top/right/bottom/left; for anything else, include the unit.
- Set a style to an empty string to remove the inline value; prefer classes for styles that describe a state.