jQuery Methods: css()

By: Dusty Arlia
Published on Tuesday, December 3, 2013, 07:59 PM
Last Updated on Saturday, July 11, 2015 at 9:04 PM
Total Updates: 2

The css() jQuery method is used to query and set CSS property values. When you query the current CSS property value, you are getting the "computed" value. The value may come from the style attribute or a stylesheet. It is not possible to query compound styles (like font, margin, or border). You must query individual properties (e.g. font-weight, margin-left, or border-style). The returned value will be a string (even if it is a number like font-weight: 900)

When using the css() jQuery method to set CSS property values, this method sets the property values on the style attribute of the HTML element. When referencing CSS property names like border-width, you can use the same CSS format (with the hyphen), or you can use the JavaScript camelcase format (borderWidth).

Here are some examples:

$("h2").css("font-size");   //get the font-size of the first <h2>
$("h2").css("fontSize");   //camelcase works too
$("div").css("border");   //Error - can't query compound styles
$("div").css("border", "1px solid red");   //But it's ok to set compound styles
$("div").css({border: "1px solid red",
			  color: "black",
			  margin: "8px"});   //you can do more than one at a time
$("#window_width_div").css("width", function() {
	//return window width
	//make this jQuery your window resize event handler