
Css in Jquery
What is .css()
in jQuery?
The .css()
method is used to either:
Get the current value of a CSS property for an element.
Set a CSS property for one or more elements.
Syntax
1. Get CSS Property Value
<div "#getColorBtn").click(function() { var color = $("#box").css("background-color"); alert("The background color is: " + color); });script>
Explanation:
Clicking the "Get Color" button will display the current background color of the
#box
element.
Example 2: Set a Single CSS Property
Now, let's set the background color of the #box
element to blue:
"#setColorBtn").click(function() { $("#box").css("background-color", "blue"); });script>
Explanation:
When the "Change Color" button is clicked, the background color of the
#box
will change to blue.
Example 3: Set Multiple CSS Properties
You can also set multiple properties at once:
"#setMultipleBtn").click(function() { $("#box").css({ "background-color": "green", "width": "200px", "height": "200px" }); });script>
Explanation:
When the button is clicked, multiple properties are set at once:
Background color changes to green
Width changes to 200px
Height changes to 200px
Special Notes
Unitless Values: For properties like
width
,height
,font-size
, etc., you can pass unitless values (e.g.,width: 100
), but jQuery will assume the default unit (px
) unless specified.$("#box").css("width", 100); // This is equivalent to 100px.
Get vs Set: If you pass just the property name as an argument, jQuery will get the value. If you pass both the property name and value, jQuery will set the value.
Use Cases for .css()
Dynamically update styles: Change styles in response to events like clicks, mouse movements, or form inputs.
Responsive design: Dynamically adjust styles based on user interactions or window resizing.
Animations and effects: Modify an element's style as part of an animation effect.
Summary
.css(property)
: Get the current value of a CSS property..css(property, value)
: Set a single CSS property..css({ property1: value1, property2: value2 })
: Set multiple CSS properties at once.