jQuery - css() Method


The method css() function is used to set or returns a style property for the chosenHTML element.

You can also search for these topics, define important jquery css method, css selector method using jquery, multiple jquery css method, example.

Return a CSS Property

The css("propertyname") function is used to get the value of a specific CSS property of a specific HTML element.

Note:- The value of the FIRST matched element will be returned, if multiple elements are found.

Syntax:

css("propertyname");

Example :-

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#b1").click(function () {
            alert("Font size = " + $("#p1").css("font-size"));
            alert("Text color = " + $("#p1").css("color"));
        });
    });
</script>
</head>
<body>

<p id="p1" style="font-size:large; color:green">This is a paragraph.</p>

<button id="b1">Get CSS Values</button>

</body>
</html>

Output :-

This is a paragraph.


You can also search for these topics, return a css selector property and value, return a css property space between elements, declare and return, css property default value returned, display inline block property, background color, max width, example.

Set a Single / Multiple CSS Property

The css("propertyname","value") function is used to set a particular CSS property of an specified HTML element or All matched elements.

Use the following syntax to assign single property:

css("propertyname","value");

Use the following syntax to assign multiple properties at once:

css({"propertyname1":"value1","propertyname2":"value2",...});

Example :-

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#b3").click(function () {
            $("#p3").css("background-color", "orange");
        });

        $("#b4").click(function () {
            $("#p3").css({ "color": "blue", "font-size": "xx-large" });
        });
    });
</script>
</head>
<body>

<p id="p3">This is a paragraph.</p>

<button id="b3">Set Background Color</button><br /><br />
<button id="b4">Set Text Color and Size</button>

</body>
</html>

Output :-

This is a paragraph.




You can also search for these topics, how to set css class property using jquery, set src property, jquery selectors to set a css property, set multiple css properties, syntax and example for set a css property, add multiple css property example, jquery set multiple css properties at once, not working.