CSS with jQuery
Learn how to get and set CSS properties dynamically using jQuery.
jQuery makes reading and changing CSS styles extremely simple with the .css() method.
Getting CSS Values
// Get a single property
let color = $("h1").css("color");
let fontSize = $("h1").css("font-size");
console.log(color, fontSize);
Setting a Single Property
$("h1").css("color", "red");
$(".box").css("background-color", "#3498db");
$("p").css("font-size", "1.2rem");
Setting Multiple Properties
$(".card").css({
"background": "white",
"padding": "1.5rem",
"border-radius": "12px",
"box-shadow": "0 4px 12px rgba(0,0,0,0.1)",
"margin-bottom": "1rem"
});
Using camelCase
You can use either CSS-style or camelCase property names:
// Both work:
$(".box").css("background-color", "blue");
$(".box").css("backgroundColor", "blue");
Dynamic Values with a Function
// Increase font size of each paragraph
$("p").css("font-size", function(index, currentValue) {
return (parseFloat(currentValue) + 2) + "px";
});
Practical Example
// Theme switcher
$("#darkMode").click(function() {
$("body").css({
"background": "#1a1a2e",
"color": "#eee"
});
$(".card").css({
"background": "#16213e",
"color": "#ddd"
});
});
$("#lightMode").click(function() {
$("body").css({
"background": "#fff",
"color": "#333"
});
$(".card").css({
"background": "#f8f9fa",
"color": "#333"
});
});
Tip: For complex styling changes, it's better to toggle CSS classes instead of using .css() directly.