Getting and Setting CSS Attributes
The css()
method is very much
like the attr()
method, but it works
with the CSS styles of an element rather than the HTML attributes of the
element. When querying style values, css()
returns the current style (or âcomputed
styleâ) of the element: the returned value may come from the style
attribute or from a stylesheet. Note
that it is not possible to query compound styles such as âfontâ or
âmarginâ. You must instead query individual styles such as
âfont-weightâ, âfont-familyâ, âmargin-topâ, and âmargin-leftâ. When
setting styles, the css()
method
simply adds the style to the elementâs style
attribute. css()
allows you to use hyphenated CSS style
names (âbackground-colorâ) or camel-case JavaScript style names
(âbackgroundColorâ). When querying style values, css()
returns numeric values as strings, with
the units suffix included. When setting, however, it converts numbers to
strings and adds a âpxâ (pixels)
suffix to them when necessary:
$("h1").css("font-weight"); // Get font weight of 1st <h1> $("h1").css("fontWeight"); // Camel case works, too $("h1").css("font"); // ERROR: can't query compound style $("h1").css("font-variant", // Set style on all <h1> tags "smallcaps"); $("div.note").css("border", // Okay to set compound styles "solid black 2px"); // Set multiple styles at once $("h1").css({ backgroundColor: "black", textColor: "white", fontVariant: "small-caps", padding: "10px 2px 4px 20px", border: ...
Get jQuery Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.