Skip to main content

Archive

Show more

jQuery CSS Properties

jQuery - CSS Properties

CSS properties are attributes that define the visual presentation of HTML elements, and jQuery allows for easy manipulation of these properties.


1. Set CSS Properties

The css() method in jQuery is used to set one or more CSS properties for the selected elements.

Example:

// Set the background color of all paragraphs to red
$("p").css("background-color", "red");

// Set the font size of all headings to 24 pixels and the text color to blue
$("h1, h2, h3").css({
    "font-size": "24px",
    "color": "blue"
});

This code sets the background color of all paragraphs to red and changes the font size and text color of all headings.


2. Get CSS Properties

The css() method can also be used to retrieve the value of a CSS property for the first element in the matched set.

Example:

// Get the background color of the first paragraph
var bgColor = $("p:first").css("background-color");

// Get the font size of the first heading
var fontSize = $("h1:first").css("font-size");

console.log("Background color: " + bgColor);
console.log("Font size: " + fontSize);

This code retrieves the background color of the first paragraph and the font size of the first heading and logs the values to the console.


3. Manipulate CSS Classes

jQuery also provides methods to manipulate CSS classes of elements, allowing for dynamic styling changes.

Example:

// Add a class to all paragraphs
$("p").addClass("highlight");

// Remove a class from all headings
$("h1, h2, h3").removeClass("underline");

// Toggle a class on all div elements
$("div").toggleClass("hidden");

In this example, the addClass() method adds a "highlight" class to all paragraphs, the removeClass() method removes the "underline" class from all headings, and the toggleClass() method toggles the "hidden" class on all div elements.


4. Conclusion

jQuery's css() method provides a convenient way to manipulate CSS properties of HTML elements, allowing developers to dynamically control the appearance of web pages. Whether setting or retrieving CSS properties, jQuery simplifies the process of working with styles.

In addition to direct CSS manipulation, jQuery also offers methods for manipulating CSS classes, providing further flexibility in styling and design.

Comments