jQuery css() Method
You are Here:
jQuery css() Method
The jQuery css()
method is used for the following 2 purpose
- To get the computed style properties for the first element in the set of matched elements.
- To set one or more CSS properties for the set of matched elements.
Get CSS
In the following example, we will get the value of the font-size of the first paragraph.
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery css() Method</h1>
<p style="font-size:20px;">Hello jQuery</p>
<button>Alert p's font-size</button>
<script>
$(document).ready(function(){
$("button").click(function(){
alert($("p").css("font-size"));
});
});
</script>
</body>
</html>
Syntax
// To get the value of specific css property
$(selector).css("property");
// To Apply one css property
$(selector).css("property", "value");
// To Apply multiple css property
$(selector).css({"property1":"value1", "property2":"value2"});
Set CSS (one property)
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery css() Method</h1>
<p>Hello jQuery</p>
<script>
$(document).ready(function(){
$("p").css("color", "red");
});
</script>
</body>
</html>
Set CSS (multiple properties)
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery css() Method</h1>
<p>Hello jQuery</p>
<script>
$(document).ready(function(){
$("p").css({"color":"red","font-size":"22px"});
});
</script>
</body>
</html>
Set CSS (as an object)
Example
HTML Editor
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>jQuery css() Method</h1>
<p>Hello jQuery</p>
<script>
var obj={
"color": "red",
"font-size": "22px",
"font-style": "italic"
}
$(document).ready(function(){
$("p").css(obj);
});
</script>
</body>
</html>
Reminder
Hi Developers, we almost covered 99.5% of jQuery Tutorials with examples for quick and easy learning.
We are working to cover every Single Concept in jQuery.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.