1. Home
image

jQuery Tutorial Concepts - From Beginner to Pro

Learn jQuery from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 19
  • 3
right-top-arrow
3

jQuery CSS

Updated on 14/08/2024344 Views

The css() method in jQuery helps you change or check the style of selected web elements. With this method, you can:

  • Set Styles: Easily apply one or more styles to elements.
  • Get Styles: Check and get the current style of elements.

It's a handy tool that gives developers more control over how their web elements look and behave.

Understanding the jQuery css() Method

The css() method in jQuery allows you to either set or retrieve one or multiple CSS style properties for the chosen elements.

Retrieving a CSS Property Value

To get the computed style property for the first matched element, you can use the syntax below:

css("propertyname");

It returns a string representing the computed style property.

Example:

$("div").css("color");

Returns the computed color of the first matched div element.

Here's another example that retrieves the background-color value of the FIRST matched paragraph element:

$("p").css("background-color");

In this example, $("p") selects all paragraph elements, and .css("background-color") fetches the background-color property value of the first paragraph in the selection.

How to set a CSS Property?

To change a specific CSS property, use this format:

css("propertyname", "value");

For instance, the code below will change the background color of ALL selected paragraphs to blue:$("p").css("background-color", "blue");

We can take another example. Which sets the color of all div elements to red:

$("div").css("color", "red");

How to set a CSS Property Based on a Function?

To set a CSS property using a function with jQuery's .css() method by using the following syntax:

css( propertyName, function )

Here's an example that increases the width of each div element by 20%:

$("div").css("width", function(index, value) {

    return parseFloat(value) * 1.2 + "px";

});

In this example:

index is the index position of the current element in the set.

value is the current value of the CSS property.

newValue is the new value you want to set.

The function calculates the new width based on the current width (value) and returns the updated value.

How to apply Multiple CSS Properties?

To apply several CSS styles at once, you can use this structure:

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

For example, the code below will update the background color to green and set the font size to 200% for ALL selected paragraphs:$("p").css({"background-color": "green", "font-size": "200%"});

Retrieving Computed Style Properties with .css()

Obtaining Computed Style Properties for the First Matched Element

Returns An object that contains the values of the specified properties.Example:$("div").css(["color", "font-size"]);

This returns an object with the color and font-size values of the first matched div element.

More about .css() Method in jQuery

  • Consistent Behavior:

The .css() method handles different naming conventions of CSS properties across browsers, ensuring consistent behavior.

  • Computed Styles:

Computed styles might differ from the values specified in stylesheets due to unit conversions like pixels, em, or %.

  • Shorthand Properties:

Retrieving shorthand CSS properties may not work with all browsers.

  • DOM Connection:

Always ensure the element is connected to the DOM when using .css(), or jQuery may throw an error.

  • jQuery 1.9 and Later:

Passing an array of properties to .css() returns an object with property-value pairs.

  • jQuery 3.2 and Later:

Support for CSS Custom Properties (CSS Variables) is available. Use $("p").css("--custom-property") to retrieve the value.

  • Handling Naming Conventions:

jQuery understands both CSS and DOM formatting for multi-word properties.

.css({ "background-color": "#ffe", "border-left": "5px solid #ccc" }) and .css({backgroundColor: "#ffe", borderLeft: "5px solid #ccc" }) are both valid.

  • Number Values:

If you pass a number, jQuery adds "px" to it. For other units, add the unit yourself.

  • Removing Styles:

To remove a style, set its value to an empty string.

$( "#mydiv" ).css( "color", "" );

  • Prefix Handling:

Since jQuery 1.8, .css() adds the correct prefix for cross-browser compatibility.

  • Relative Values:

Since jQuery 1.6, you can use relative values.

.css( "padding-left", "+=15" )

This increases the padding-left by 15 pixels.

  • CSS Custom Properties:

From jQuery 3.2 onwards, you can use CSS Custom Properties (CSS Variables).

$( "p" ).css( "--custom-property", "value" )

  • Important Declarations:

.css() doesn't support !important declarations.

Examples:

1. How to get the background color of a clicked div?

<script>

$("div").on("click", function() {

  var color = $(this).css("background-color");

  $("#result").html("That div is <span style='color:" + color + ";'>" + color + "</span>.");

});

</script>

2. How to get the width, height, text color, and background color of a clicked div?

<script>

$("div").on("click", function() {

  var width = $(this).css("width");

  var height = $(this).css("height");

  var textColor = $(this).css("color");

  var bgColor = $(this).css("background-color");

 $("#result").html("Width: " + width + "<br>Height: " + height + "<br>Text Color: " + textColor + "<br>Background Color: " + bgColor);

});

</script>

3. How to change the color of any paragraph to red on mouseover event?

<script>

$("p").on("mouseover", function() {

  $(this).css("color", "red");

});

</script>

4. How to increase the width of #box by 200 pixels the first time it is clicked?

<script>

$("#box").one("click", function() {

  $(this).css("width", "+=200");

});

</script>

5. How to change the font weight and background color on mouseenter and mouseleave?

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>CSS Demo</title>

  <style>

  div {

    width: 100px;

    height: 50px;

    background-color: #3f3;

    margin: 10px;

    text-align: center;

    line-height: 50px;

    cursor: pointer;

    font-weight: normal;

  }

  </style>

  <script src="https://code.jquery.com/jquery-3.7.0.js"></script>

</head>

<body>

<div>Hover Over Me</div>

<script>

$( "div" ).on({

    mouseenter: function() {

        $(this).css({

            'font-weight': 'bold',

            'background-color': '#33f'

        });

    },

    mouseleave: function() {

        $(this).css({

            'font-weight': 'normal',

            'background-color': '#3f3'

        });

    }

});

</script>

</body>

</html>

In this example:

  • The font weight of the <div> changes to bold and its background color changes to blue when hovered over.
  • The font weight returns to normal and the background color reverts to green when the mouse leaves the <div>.

6. How to change the Border Color and Width?

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>CSS Demo</title>

  <style>

  div {

    width: 100px;

    height: 50px;

    background-color: #3f3;

    margin: 10px;

    text-align: center;

    line-height: 50px;

    cursor: pointer;

    border: 2px solid black;

  }

  </style>

  <script src="https://code.jquery.com/jquery-3.7.0.js"></script>

</head>

<body>

<div>Hover Over Me</div>

<script>

$( "div" ).on({

    mouseenter: function() {

        $(this).css({

            'border-color': 'blue',

            'border-width': '4px'

        });

    },

    mouseleave: function() {

        $(this).css({

            'border-color': 'black',

            'border-width': '2px'

        });

    }

});

</script>

</body>

</html>

7. How to change Font Size and Background Color using .hover()

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>CSS Demo</title>

  <style>

  div {

    width: 100px;

    height: 50px;

    background-color: #3f3;

    margin: 10px;

    text-align: center;

    line-height: 50px;

    cursor: pointer;

    font-size: 16px;

  }

  </style>

  <script src="https://code.jquery.com/jquery-3.7.0.js"></script>

</head>

<body>

<div>Hover Over Me</div>

<script>

$( "div" ).hover(

    function() {

        $(this).css({

            'font-size': '20px',

            'background-color': '#33f'

        });

    },

    function() {

        $(this).css({

            'font-size': '16px',

            'background-color': '#3f3'

        });

    }

);

</script>

</body>

</html>

In this example:

  • The font size of the <div> increases to 20px and its background color changes to blue when hovered over.
  • The font size reverts to 16px and the background color reverts to green when the mouse leaves the <div>.

Conclusion

The jQuery .css() method is a powerful tool that lets developers change the style of HTML elements on-the-fly. It's versatile and efficient, enhancing the interactivity and responsiveness of web pages.

Key Features of jQuery's .css() Method:

  • Allows for real-time updates to the style of selected elements.
  • Enables the setting or retrieval of one or multiple CSS properties.
  • Supports a wide range of CSS properties and values, including relative measurements and custom CSS variables.

When used in conjunction with standard CSS, the .css() method in jQuery empowers developers to craft dynamic and visually engaging web interfaces, facilitating the creation of more interactive and responsive websites.

FAQs

Q. Can you use jQuery in CSS?
jQuery cannot be directly integrated into CSS, as it is a JavaScript library primarily used to streamline client-side scripting.
jQuery can be employed to dynamically adjust the CSS attributes of HTML elements. This approach is frequently utilized to implement dynamic styling in response to user interactions or specific conditions.

Q. Why use jQuery instead of CSS?
jQuery and CSS do different jobs in web design, but they work well together:

  • jQuery can change website content, works well in all browsers, adds animations, handles user clicks easily, supports dynamic data loading, and has lots of extra features and tools.
  • CSS is mainly for making things look good but doesn't change content dynamically.

In short, CSS makes things look nice, while jQuery makes websites more interactive. They're often used together in web design.

Q. How to add a CSS file in jQuery?
You can't directly add a CSS file using jQuery, you can use jQuery to dynamically modify or add CSS styles. To link an external CSS file to your HTML document, you would use the <link> tag within the <head> section.

Q. Does jQuery use CSS selectors?
Yes, jQuery uses CSS selectors to target and manipulate DOM elements, making it easier for developers to select and modify elements using familiar CSS syntax.

Q. Can I still use jQuery?
Yes, you can still use jQuery. It's a widely used tool for web development, although newer frameworks are also available for more modern projects.

Q. What is the CSS equivalent of jQuery?
The CSS equivalent of jQuery is not direct because they have different purposes:

  • jQuery is for DOM manipulation and event handling.
  • CSS is for styling web pages.

For JavaScript-based DOM manipulation without jQuery, you can use the built-in methods in modern JavaScript or a lightweight library like Zepto.js.

image

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...