jQuery provides methods to retrieve and modify CSS style properties directly. We keep these methods in three sets. The first set discusses methods that allow us to retrieve CSS properties. The second set discusses methods that allow us to alter CSS properties. The third set discusses methods that deals with CSS properties for lists.
The first table lists all the methods that allow us to retrieve the value of a CSS property.
Method | Description |
---|---|
.css(prop(s)) | Retrieves the value of the CSS "property"; applies to multiple properties |
.height() | Retrieves the height (without "px" unit) |
.width() | Retrieve the width (without "px" unit) |
.innerHeight() | Retrieves the height excluding the border (without "px" unit) |
.innerWidth() | Retrieves the width excluding the border (without "px" unit) |
.outerHeight(boolMargin) | Retrieves the height including the border (without "px" unit) |
.outerWidth(boolMargin) | Retrieves the width including the border (without "px" unit) |
.scrollLeft() | Retrieves the horizontal position of the scroll bar |
.scrollTop() | Retrieves the vertical position of the scroll bar |
.offset() | Retrieves the offset (an object with top/left coordinate properties) |
.position() | Retrieves the position as an object with top/left coordinate properties |
The first method in the above table, ".css(prop)" returns the value associated with the CSS "prop" property. With jQuery 1.9 version, we can also pass multiple properties to this method: ".css(prop1, prop2, prop3, ..)" and the method will return a JavaScript object (not a jQuery list!) which has the name of these properties as keys and the CSS value of corresponding property as value.
While the .css() method is generic, rest of the methods are more specific.
The ".height()" method returns the height (in pixels) of the selected element. The ".width()" method returns the width (in pixels) of the selected object. The ".innerHeight()" and ".innerWidth()" methods return the height/width (in pixels) of the selected object without including the border. Alternatively, the ".outerHeight()" and ".outerWidth()" methods return the height/width (in pixels) of the selected object and include the border. The methods, ".scrollLeft()" and ".scrollTop()" return the horizontal/vertical positions (in pixels) of the scroll bar, respectively.
The last two methods, ".offset()" and ".position()", are similar but have an important difference. They both return an object that has two keys (namely, top and left) and these keys represent the coordinate value from the top and the left. However, the ".position()" method returns the current position of the object relative to the document and the ".offset()" method returns the current position of the element relative to the offset parent.
For some of the CSS properties, we can use the .css() method and pass the corresponding property or use the corresponding method directly, if it exists. For example, to get the height of an object, we can use either .css("height") or the .height() method. When we use the .css("height"), we get the height along with "px" text appended in the end (e.g. 100px). But, when we use the .height(), we get the height without the "px" text appended (e.g. 100). If we need to use the output in mathematical calculations, then we should use the corresponding method. Needless to say, if we use the .css() method, then we should remember to strip the "px" text appended in the end.
With that, we are now armed to see our first example. For the sake of clarity, we split the example into two parts. The first part is the HTML structure. The second part is the included JavaScript file houses the jQuery logic. For other examples on this page, we plan to keep the HTML page same and simply update the included JavaScript file to update the logic. The HTML structure is an ordered list (identified by the "classOl" class) that has three child list items. Each of these child list items has its own class. The HTML page includes both the jQuery library and a JavaScript page ("properties.js").
Lastly, the page contains an HTML anchor, "CSS Properties" -- we will use this anchor to attach a click event that will trigger the accompanying jQuery logic. Please note that instead of an anchor, we could have also used a button element.
<!doctype html> <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script> <body> <style type="text/css" class="classStyles"> .classRed {color: red} .classGreen {color: green} .classBlue {color: blue} </style> <div>Nobel Laureates:</div> <ol class="classOl"> <li class="classRed">Marie Curie (Chemistry, 1911)</li> <li class="classGreen">Albert Einstein (Physics, 1921)</li> <li class="classBlue">Mother Teresa (Peace, 1979)</li> </ol> <script type="text/javascript" src="properties.js"></script> <a id="idAnchor" href="#">CSS Properties</a><br> </body> </html>
The included "properties.js" file (provided below) demonstrates some of the above methods. It uses the ".css()" method to get the height, width, color, and background-color CSS properties of the ordered list, which is identified using the "classOl" CSS class. We also use .height(), .width(), and .offset() methods to get corresponding properties directly.
We also demonstrate that we can pass a set of CSS properties to the .css() method. This method returns a JavaScript object that has passed properties as keys and their values as the corresponding key values. Please note that the returned value is a JavaScript object and not a jQuery list so using .each() method would not work! If you are wondering why not a list, then the answer is that we need to return a list of key/value pairs and not a list of values -- a JavaScript object holds key/value pairs and so it is the logical choice. Here is the "properties.js" file.
// Filename: properties.js $(document).ready(function() { $("#idAnchor").click( function() { var prop, str = ""; prop = $(".classOl").css("height"); str += "The height (using .css() method) is: " + prop + "<br>"; prop = $(".classOl").height(); str += "The height (using .height() method) is: " + prop + "<br><br>"; prop = $(".classOl").css("width"); str += "The width (using .css() method) is: " + prop + "<br>"; prop = $(".classOl").width(); str += "The width (using .width() method) is: " + prop + "<br><br>"; prop = $(".classOl").css("color"); str += "The color (using .css() method) is: " + prop + "<br>"; prop = $(".classOl").css("background-color"); str += "The background-color (using .css() method) is: " + prop + "<br>"; prop = $(".classOl").offset(); str += "The offset (using .offset() method) is: top: " + prop.top + " and left: " + prop.left + "<br><br>"; // This method was added in jQuery version 1.9. prop = $(".classOl").css(["height", "width", "color", "background-color"]); for (elem in prop) { str += elem + ": " + prop[elem] + "<br>"; } $("body").append(str + "<br>"); }); });
Here is how the page looks like before we click the "CSS Properties".
With that, we are all set. Let us now click the "CSS Properties". Upon doing so, we would see the value of the height, width, background-color, and offset properties. As noted earlier, when using the .css() method, we also get the "px" appended to the output. Here is the output:
Where as the earlier methods allow us to retrieve CSS properties, our next table shows that we can use (most of) these methods to also alter CSS properties. For that, we need to simply pass the CSS property value as an additional argument.
Method | Description |
---|---|
.css(prop, val) | Updates the CSS "property" with the passed value |
.css(propList) | List of properties that need to be updated along with their value |
.height(val) | Updates the height with the passed value |
.width(val) | Updates the width with the passed value |
.offset(obj) | Updates the offset with the passed object (should hold top/left properties) |
.scrollLeft(val) | Updates the horizontal position of the scroll bar with the passed value |
.scrollTop(val) | Updates the vertical position of the scroll bar with the passed value |
In the above table, we can use the .css(prop, val) method to set the value of "prop" property to "val". In fact, we can pass an object with key/value pairs, where the keys represent the CSS properties and the values represent, well, their values!
The other methods, .height(val), .width(val), .scrollLeft(val), .scrollTop(val), when invoked with a value, set the corresponding CSS property to the specified value. The .offset() methods accepts an object that has two keys (namely, top and left) and their values represent the coordinate values from the top and the left of the document. Note that, three methods from the earlier table. .innerHeight(), .innerWidth(), and .position() do not accept any argument and hence, cannot be used to modify the CSS properties.
For .height() and .width() methods, if we do not pass any explicit unit, (e.g 'em' or '%'), then jQuery adds "px" to the end of the value; with .css() method, we need to add "px".
At this point, we are ready to see our next example. To do so, we modify the earlier "properties.js" file and reuse the earlier HTML structure. The new "properties.js" file (provided below) uses the above methods to modify some of the CSS properties.
// Filename: properties.js $(document).ready(function() { $("#idAnchor").click( function() { var prop, str = ""; $(".classOl").css("height", "100px"); str += "The height is: " + $(".classOl").css("height") + "<br>"; $(".classOl").height(200); str += "The height is: " + $(".classOl").height() + "<br>"; $(".classOl").css("width", "1800px"); str += "The width is: " + $(".classOl").css("width") + "<br>"; $(".classOl").width(2000); str += "The width is: " + $(".classOl").width() + "<br>"; offsetObj = {top: 100, left: 50} $(".classOl").offset(offsetObj); prop = $(".classOl").offset(); str += "The offset is: top: " + prop.top + " and left: " + prop.left + "<br><br>"; $("body").append(str + "<br>"); }); });
Here is the output when we click the "CSS Properties" link. We can see that we have successfully modified the height, width, and offset values of the ordered list.
All of the above methods can also be applied to list elements. The problem is that when we do so, the earlier forms of these methods will apply only to the first member of the list. Thus, if we have several elements in an HTML list, then $("li") will return a list of all those elements and $("li").css("color") will return the "color" property for the first list element only. This behavior applies when we try to retrieve CSS properties or when we try to modify them.
To address that, we have a new form of these methods. In the new variant, we can pass a function that can work on a list. The function returns the value that it wishes to set for the list elements. The last table (provided below) revisits some of the earlier methods that can be used with lists. The first argument of these functions is an index argument that points to the current index of a list element. The second argument is the current value of the CSS property of the current list element. When the function is invoked, the variable "this" represents the current list item.
Here is the table:
Method | Description |
---|---|
.css(prop, function(indx, val) {}) | Updates CSS "property" of list elements |
.height(function(indx, val) {}) | Updates height of list elements with the returned value |
.width(function(indx, val) {}) | Updates width of list elements with the returned value |
.offset(function(indx, obj) {}) | Updates the offset of list elements with the returned offset obj |
In addition to the function as an argument, the .css() method accepts yet another argument: the name of the CSS property that we wish to change for each of the list element.
To demonstrate the usage of these function-based methods, let us update the "properties.js" file again; the example continues to use the same basic HTML structure. The "properties.js" file now loops through these elements and prints the existing CSS "color" and "height" properties for each element.
// Filename: properties.js $(document).ready(function() { $("#idAnchor").click( function() { var prop, str = "", colorCodes = ["crimson", "darkorange", "magenta"]; str += "Color<br>"; $("li").css("color", function(index, val) { str += "Index: " + index + ", Existing Value: " + val + "<br>"; return colorCodes[index]; }); str += "<br>Height<br>"; $("li").height(function(index, val) { str += "Index: " + index + ", Existing Value: " + val + "<br>"; return (25 * index + 25); }); $("body").append(str + "<br>"); }); });
And here is the output when we click the "CSS Properties" link. From the output, we can see that different list elements now have different font-colors. In addition, we also see that the height of various elements are also different.