Advertisement

Google Ad Slot: content-top

jQuery css()


jQuery css() Method

The .css() method is used to get or set one or more CSS properties of selected elements.


jQuery .css() method is one of the most powerful and convenient tools for manipulating styles directly with JavaScript


Return a CSS Property

To return (get) a CSS property value using jQuery’s .css() method, use the following syntax:


$(selector).css("property-name");


he following example will return the color value of the div element:

Example
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Background color = " + $("div").css("background-color"));
});
});
</script>
Try it yourself

To set a CSS property in jQuery, you use the .css() method and provide the property name and value as arguments.


Syntax:


$(selector).css("property-name", "value");


The following example will set the background-color value for selected elements:

Example
<script>
$(document).ready(function(){
$("button").click(function(){
$("#box").css("background-color", "yellow");
});
});
</script>
Try it yourself

Set Multiple CSS Properties


jQuery makes it super easy to set multiple CSS properties at once using the .css() method with an object.


Syntax:


css({"propertyname":"value","propertyname":"value",...});


The following example will set a background-color and a font-size for selected elements:

Example
<script>
$(document).ready(function(){
$("button").click(function(){
$("#box").css({
"background-color": "black",
"color": "white",
"padding": "20px",
"border-radius": "10px"
});
});
});
</script>
Try it yourself

Note

Use camelCase for properties if you prefer (e.g., fontSize instead of font-size) — both work: