jQuery css()

The jQuery css() method is used to get or set the CSS properties of elements. It allows you to dynamically apply inline styles to elements or retrieve their computed style values.

Key Topics

Getting CSS Properties

Use the css() method with a property name to get the current computed value of a CSS property.

var color = $("#element").css("color");

Explanation: This code retrieves the text color of the element with the ID element.

Setting CSS Properties

Use the css() method with a property name and value to set a new CSS property.

$("#element").css("color", "blue");

Explanation: This code sets the text color of the element with the ID element to blue.

Setting Multiple Properties

You can set multiple CSS properties at once by passing an object with key-value pairs.

$("#element").css({
    "color": "green",
    "font-size": "20px",
    "background-color": "yellow"
});

Explanation: This code sets multiple styles for the element with the ID element, including text color, font size, and background color.

Example: Using css()


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery css() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <p id="text">This is a sample paragraph.</p>
    <button id="styleButton">Apply Styles</button>

    <script>
        $(document).ready(function() {
            $("#styleButton").click(function() {
                $("#text").css({
                    "color": "white",
                    "font-size": "18px",
                    "background-color": "black"
                });
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example uses the css() method to change the color, font size, and background color of a paragraph element when a button is clicked.

Key Takeaways

  • Dynamic Styling: Use css() to dynamically retrieve or update CSS properties.
  • Efficiency: Set multiple properties at once with an object for better code organization.
  • Flexibility: Works seamlessly for inline styles and computed properties.