jQuery CSS Method – The Complete Guide with Examples

jQuery CSS Method – The Complete Guide with Examples

The jQuery CSS Method returns the CSS Style property value of the first matched element. It can also set, single or multiple CSS Style properties on the selector.

Note that the selector can itself be a single or multiple elements.

Syntax of jQuery CSS Method

There are 5 syntax of this method, you can use anyone of them depending upon the situation.

=> Returns a CSS Style Property Value of the first matched element:

$(selector).css(property)

=> Returns Multiple CSS Style Properties Value of the first matched element:

$(selector).css([property1, property2, property3,...])

=> Sets a Single CSS Style Property on the selector:

$(selector).css(property, value)

=> Sets a Single CSS Style Property on the selector using a function:

$(selector).css(property, function(index,currentvalue){})

=> Sets Multiple CSS Style Properties on the selector:

$(selector).css({property:value, property:value, property:value, ...})
Parameter Description
Parameter Description
Property The CSS property – like “height”, “width”, “color”, “font-weight”, etc.
Value The CSS property value – like “20px”, “Orange”, “bold”, etc
function(index,value) It returns the value to set on the current element. Index for the index position of the element and Value for the current value for the element.
The jQuery CSS method will always return the dimensions (width, height, margin, padding, etc) in px even when they are specified as em, ex or %. The color is always retuned in rgb() format.
You would also love to know the jQuery .grep() method which is used to filter an array based on a provided condition. You can create any such condition based on the filter logic of your application.

Example 1: Return a CSS Style Property

Click the Blue Circle

 

Click Me

 

 

Let us get the CSS property of a div from jQuery CSS method. Here I have this div with class as blueBoxDiv.

<div class="blueBoxDiv">
</div>

It has the CSS Properties given below:

.blueBoxDiv {
    background-color: blue;
    height: 100px;
    width: 120px;
    font-size: 10px;
}

I can use jQuery CSS method to get the value of background-color property:

console.log("Background Color: " + $(".blueBoxDiv").css("background-color"));

Example 2: Return Multiple CSS Style Properties

Click any Figure

 

Click Me

Click Me

Click Me

Click Me

I have 4 rounded figures of color blue, red, yellow and purple and I want to get their width, height, background-color and font-size whenever someone clicks on them.

The HTML of these 4 figures are:

<div class="multipleBoxDiv">
    <div class="blueBoxDiv">
        <p>Click Me</p>
    </div>
    <div class="redBoxDiv">
        <p>Click Me</p>
    </div>
    <div class="orangeBoxDiv">
        <p>Click Me</p>
    </div>
    <div class="purpleBoxDiv">
        <p>Click Me</p>
    </div>
</div>

Their CSS Styles are:

.blueBoxDiv {
    background-color: blue;
    height: 100px;
    width: 120px;
    font-size: 10px;
}
.redBoxDiv {
    background-color: red;
    height: 120px;
    width: 130px;
    font-size: 11px;
}
.orangeBoxDiv {
    background-color: orange;
    height: 80px;
    width: 70px;
    font-size: 12px;
}
.purpleBoxDiv {
    background-color: purple;
    height: 250px;
    width: 230px;
    font-size: 13px;
}

I create the click event on these 4 divs by using their parent div called multipleBoxDiv:

$(".multipleBoxDiv > div").click(function (e) {
    var propertyValue = $(this).css(["width", "height", "background-color", "font-size"]);
    var textInfo = "The div has following CSS Styles:<br/>";
    $.each(propertyValue, function (index, value) {
        textInfo += index + ": " + value + "<br/>";
    });
 
    alert(textInfo);
});

Explanation
On the click event, I fetch the CSS Style properties by passing them as array in the jQuery CSS method – (css([“width”, “height”, “background-color”, “font-size”])) .

Then I am looping through each of them with jQuery Each method and adding the result in a text variable called textInfo.

Finally showing the value through alert statement.

The .css() Method does not work on !important. So $(“div”).css( “color”, “orange !important” ) will not turn all div elements to red color.

Example 3: Sets a Single CSS Style Property

Bring The Mouse

♥ Over Here

♥ Over Me Too

Let me show you how to change the CSS property of two paragraphs when mouse pointer is put over it.

The paragraph element:

<p class="singleCSSParagraph">Over Here</p>
<p class="singleCSSParagraph">Over Me Too</p>

The jQuery .css() method:

$(".singleCSSParagraph").mouseover(function (e) {
    $(this).css("color", "Orange");
});
 
$(".singleCSSParagraph").mouseout(function (e) {
    $(this).css("color", "");
});

I have used mouseover jQuery event to change the color to orange. Then with the mouseout event I am simply giving empty value to color, this will remove the Color CSS Property from the element (and it will be as it was previously).

The jQuery .css() method can be used to remove a Inline CSS Style from an element. For this you need to pass empty string (“”) for the CSS property. Example – this code will remove the inline style width from the selector: $(selector).css(“width”,””)

Example 4: Sets Multiple CSS Style Properties

Blue Circle

Multiple CSS Style Properties of selector can also be changed with the jQuery .css() method.

I have a circular Blue Circular figure and on button click I will change it to a Violet Square.

The HTML code of this blue box is:

<div class="blueBoxDiv">
    <p>Blue Circle</p>
</div>

The CSS Style applied on it is:

.blueBoxDiv {
    border-radius: 75px;
    background-color: blue;
    margin: 5px;
    height: 100px;
    width: 120px;
    font-size: 10px;
    cursor: pointer;
}
    .blueBoxDiv p {
        padding: 37px 0 0 10px;
        font-weight: bold;
        color: #FFF;
    }

I change the CSS properties on the click event of this figure:

$(".blueBoxDiv").click(function (e) {
    var figureType = $(this).find("p").text();
 
    if (figureType == "Blue Circle") {
        $(this).css({ "background-color": "violet", "border-radius": "0" });
        $(this).find("p").text("Violet Square");
    }
    else {
        $(this).css({ "background-color": "blue", "border-radius": "75px" });
        $(this).find("p").text("Blue Circle");
    }
});

Explanation

In the variable figureType I am fetching the text of the child paragraph of the blueBoxDiv. This helps me in knowing what figure the div currently is showing.

If the figureType contains Blue Circle then I apply jQuery CSS to change it to Violet Square. I do this by changing its background color to violet and border radius to 0px.

You should see how I passed both the properties within curly brackets in name-value pairs.css({ “background-color”: “violet”, “border-radius”: “0” })

Similarly if figureType contains Violet Square then I make the div Blue Circle again.

Learn how to implement an API with jQuery – Implementing TheMovieDB (TMDB) API with jQuery AJAX

Example 5: Using jQuery CSS Method’s Function Parameter

Passing function to the jQuery CSS parameter is very useful in situations where you want to know the old value of the selector.

See the below 2 examples.

Using Function for Changing a CSS Property of an Element

♥ Click to increase the left padding by 40px

Suppose I have a Paragraph element and on its click event I want to increase the left padding by 40px. Here I will use the function parameter of the jQuery CSS method.

The Paragraph Element is:

<p id="singleCSSFunction">♥ Click to increase the left padding by 40px</p>

The jQuery CSS code:

$("#singleCSSFunction").click(function (e) {
    $(this).css("padding-left", function (index, value) {
        return parseInt(value.replace("px", "")) + 40;
    });
});

Explanation
By using the function parameter I can know the old padding-left property’s value of the paragraph. In-fact the variable’s value will contain the old value.

I have added 40 to the value and returned it, and this will set the padding-left property.

So every time I click the Paragraph the padding-left value will increased by 40 pixels.

Note – The padding-left is a dimension, the jQuery CSS needs dimensions in pixels without the unit (px). This is the reason why it did not returned px string.

Using function for relatively Changing a CSS Property of Multiple Elements

First Paragraph

Second Paragraph

Third Paragraph

Fourth Paragraph

Fifth Paragraph

With the function parameter you can loop through all the elements in the selector and set their CSS property relative to one another.

For example I have 5 Paragraph elements and I want to move them to the right by 40 pixels to one another.

That means I want to set the padding-left property of the –

  • First Paragraph to 0px
  • Second Paragraph to 40px
  • Third Paragraph to 80px
  • Fourth Paragraph to 120px
  • Fifth Paragraph to 160px

The HTML code:

<div class="relativeDiv">
    <p>First Paragraph</p>
    <p>Second Paragraph</p>
    <p>Third Paragraph</p>
    <p>Fourth Paragraph</p>
    <p>Fifth Paragraph</p>
</div>
<button id="myButton">Try</button>

The jQuery CSS Code:

$("#myButton").click(function (e) {
    $(".relativeDiv p").css("padding-left", function (index, value) {
        return index * 40;
    });
});

Explanation
On the button click the function parameter will loop through every Paragraph element that lie inside the relativeDiv and set their padding-left in the multiples of their index.

Since I have 5 paragraphs therefore the index will start from 0 to 4.

  • So for the first paragraph padding-left value will be 0 * 40 = 40 pixels.
  • Second paragraph padding-left value will be 1 * 40 = 40 pixels.
  • Third paragraph – 2 * 40 = 80 pixels.
  • Fourth paragraph – 3 * 40 = 120 pixels.
  • Fifth paragraph – 4 * 40 = 160 pixels.

Do check the below download link:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate