How to Set a Single CSS Property in jQuery
This article provides a quick guide on how to change a single CSS
style on an HTML element using jQuery. You will learn the standard
syntax for the .css() method, understand its core
parameters, and see practical code examples demonstrating how to apply
style changes dynamically to your webpage elements.
The Syntax
To set a single CSS property on a targeted element, use jQuery's
.css() method with the following syntax:
$("selector").css("propertyName", "value");Parameter Breakdown
"selector": Specifies the HTML element or elements you want to target (such as an ID, class, or tag name)."propertyName": The name of the CSS property you wish to alter. This can be written in standard CSS kebab-case (e.g.,"background-color") or JavaScript camelCase (e.g.,"backgroundColor")."value": The new value assigned to the specified CSS property. If the value includes units (such aspx,em, or%), it should be passed as a string.
Practical Examples
Changing Text Color
To change the text color of all paragraph elements to blue:
$("p").css("color", "blue");Changing Background Color
To change the background color of an element with the ID
main-container to light gray:
$("#main-container").css("background-color", "#f0f0f0");Alternatively, you can use camelCase:
$("#main-container").css("backgroundColor", "#f0f0f0");Modifying Dimensions
To set the font size of an element with the class
highlight to 20 pixels:
$(".highlight").css("font-size", "20px");If you provide a numeric value without specifying units for dimensions, jQuery automatically treats it as pixels:
$("#banner").css("width", 500); // Sets the width to 500px