jQuery css() Method

The jQuery css() method facilitates the manipulation of CSS properties for selected elements. It offers the ability to retrieve or update styling attributes, allowing for dynamic changes in appearance. Here are examples illustrating the usage of the css() method:

Getting CSS Property

Consider an HTML paragraph (<p>) element with a defined class:

<p class="myText">This is a paragraph.</p>

To retrieve the value of a specific CSS property using jQuery:

var fontSize = $(".myText").css("font-size"); console.log(fontSize); // Output: The computed font size of the paragraph

Setting CSS Property

You can use the css() method to modify the value of a CSS property:

$(".myText").css("color", "blue");

This will change the text color of the paragraph to blue.

Setting Multiple CSS Properties

To set multiple CSS properties at once, pass an object with property-value pairs:

$(".myText").css({ "font-size": "18px", "line-height": "1.5" });

In this case, both font size and line height of the paragraph will be updated.

Calculating Values

The css() method can also calculate values, especially for numeric properties:

var currentWidth = $(".myText").css("width"); var newWidth = parseFloat(currentWidth) + 50; $(".myText").css("width", newWidth + "px");

In this example, the width of the paragraph will increase by 50 pixels.

Chaining Multiple Properties

You can chain multiple css() calls to modify multiple properties sequentially:

$(".myText") .css("font-weight", "bold") .css("text-transform", "uppercase");

This will set the font weight to bold and transform the text to uppercase.

Conclusion

The css() method offers a dynamic way to alter styling attributes, making it easy to create responsive and interactive designs. It's important to note that while css() is effective for one-time changes, for classes or repeated changes, applying and removing classes via addClass() and removeClass() may be a more structured approach.