</>
Skip to content
jQuery lessons (21/39)

jQuery — CSS

Get CSS Value

var color = $("h1").css("color");
var width = $("div").css("width");
console.log(color, width);

Set Single CSS Property

$("h1").css("color", "red");
$("div").css("background-color", "#f0f0f0");

Set Multiple Properties

$("h1").css({
    color: "red",
    "font-size": "24px",
    "background-color": "#f0f0f0",
    border: "1px solid #ccc"
});

CSS vs addClass

/* In stylesheet */
.highlight { color: red; font-weight: bold; }
// Better: use classes
$("h1").addClass("highlight");

// Inline (avoid when possible)
$("h1").css({ color: "red", "font-weight": "bold" });

Relative CSS Values

$("div").css("width", "+=50px");
$("div").css("opacity", "-=0.1");

Practical Examples

// Responsive font size
$("h1").css("font-size", function() {
    return $(window).width() < 600 ? "16px" : "24px";
});

// Dynamic background
$("body").css("background-color", "rgb(" +
    Math.floor(Math.random() * 255) + "," +
    Math.floor(Math.random() * 255) + "," +
    Math.floor(Math.random() * 255) + ")"
);

Mini Practice

  1. Get an element's current color
  2. Set multiple CSS properties
  3. Use relative CSS values
  4. Change CSS based on screen size

Up Next

Continue with Dimensions — getting element width, height, and position.

Related Topics

Frequently Asked Questions about CSS

What is CSS in jQuery?

CSS is a fundamental concept in jQuery. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn CSS?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn CSS.

Why is CSS important in jQuery?

CSS is essential for jQuery development. Understanding this concept will help you write better code and solve real-world problems more effectively.